chore: integrate repaired main into PCAP experiment review

Integrate upstream documentation/static fixes and current Windows descriptor admission without changing the measured runtime or experiment results. Preserve the reviewed rename, retry and foreign replacement ownership probe.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
This commit is contained in:
N0zoM1z0
2026-10-13 21:21:09 +00:00
co-authored by factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> Kaoru0822
348 changed files with 43603 additions and 1023 deletions
@@ -31,6 +31,49 @@ Diagnose the observed blocker, continue useful supported work, and resume the
original task after repair. Client approval, shell PATH, registration and engine
availability have different remedies; avoid repeating setup for all of them.
1. Diagnose without changing REA or client configuration. `npx` may download
the package and write to npm's cache. For Codex, run
`npx -y rea-agents@latest doctor --client codex --json`. Substitute the current
supported client: `claude_code`, `claude_desktop`, `codex`, `cursor`,
`gemini_cli`, `windsurf`, `devin`, `opencode`, `antigravity`, `copilot_cli`,
`commandcode`, `vscode`, `grok_build`, `omp`, or `grok_bot`. `grok_bot` has no local
file registration: doctor reports the Grok Bot chat step, and setup does not
write `mcp.json`. If the client is unknown, use `doctor --json` and
inspect its registration results before choosing a setup scope.
2. Distinguish the reason. Missing, malformed, or stale registration needs a
scoped configuration repair. An aligned registration with no tools in the
active session needs a restart/reconnection; doctor cannot prove that the
current agent has connected. A missing provider affects only tasks requiring
that provider: static JavaScript inspection needs neither Hopper nor Ghidra,
and Android inspection has separate bring-your-own JADX/Java prerequisites.
3. For a configuration repair, prepare the read-only plan:
`npx -y rea-agents@latest setup --client codex --dry-run --json`.
Use the current client's ID, show its exact proposed paths, backups, and
changes, and obtain approval before setup writes configuration or installs
Hopper. Setup normally installs the matching bundled skill too; include that
replacement in the reviewed plan. After approval, apply the same scope with
`npx -y rea-agents@latest setup --client codex --yes`. Add `--install-hopper`
only if that separate installation was needed and explicitly approved.
4. Restart/reconnect the affected agent. Verify that REA tools actually appear
in the session, then resume the original investigation. If they remain
absent, inspect the client's MCP launch error rather than repeating setup.
REA setup never installs or upgrades Node.js, npm, Homebrew, Java, Ghidra, IDA,
JADX, Binwalk, or Unblob. Use existing prerequisites; do not install unrelated
software to repair
MCP registration. For an unsupported client, use manual stdio registration
with a version-pinned `rea-agents` package or continue through the CLI.
A concrete CLI fallback for an operator-supplied JavaScript tree or ASAR is:
```bash
npx -y rea-agents@latest analyze-javascript-application /absolute/path/to/app --json
```
No MCP registration or native engine is required. Read the returned Evidence,
graph, limitations, and unknowns with the same care as an MCP result; the CLI
returns the Evidence record directly. This fallback does not establish that
MCP is configured. Native CLI tasks still require their selected engine.
Prefer an existing `rea` CLI. When none is installed and REA package acquisition
is within the authorized scope, use `npx -y rea-agents@latest` in its place.
Configuration repair starts with a read-only setup plan; show paths, backups and
@@ -122,6 +165,14 @@ explicit path or endpoint and do not need it.
absent metadata does not prove a binary is not Go, and unparsed text records
remain explicit. See the
[Go binary guide](https://github.com/morluto/rea/blob/main/docs/go-binaries.md).
- Embedded cargo-auditable Rust dependency metadata: `inspect_rust_binary`
with the explicit local ELF, PE, or thin Mach-O file. This built-in
target-free inspection requires no Rust installation or disassembler. Preserve
package order, dependency indices, and the section file range. A missing
`.dep-v0` section is null metadata, not proof the binary has no dependencies.
A rustc commit hash is an inference from a read-only `/rustc/<40-hex>/` path.
See the
[Rust binary guide](https://github.com/morluto/rea/blob/main/docs/rust-binaries.md).
- Explicit local SQLite database snapshot: `inspect_sqlite_database`. Inspect
with Node.js 24.x >=24.15 or 26+ providing native SQLite limits. Read schema
@@ -65,3 +65,7 @@ Use `inspect_analysis_view` with `view: {kind: "api-surface"}` on retained
method, origin and path template. Format matches are inferences, not handler
identity or schemas. Group pages cite parent record ordinals; consult record
coverage and exclusions before claiming completeness. No requests are replayed.
When the connected schema advertises `include_query_parameter_names`, select
it in the view for distinct observed names with original record ordinals. Query
values are omitted; the names establish neither required parameters nor a
complete server schema. Keep the original parent Evidence for exact URLs.
@@ -11,6 +11,18 @@ unparsed module-text line. A missing record is an unknown, not proof of a
non-Go binary; observed metadata does not authenticate its claims. Function,
source and type recovery remain a separate native-analysis question.
## Rust dependency metadata
Use `inspect_rust_binary` for an explicit local ELF, PE, or thin Mach-O when
the question concerns the cargo-auditable crate list embedded in `.dep-v0`
(Mach-O: `__DATA,.dep-v0`). No `open_binary`, Rust installation, or target
execution is required. The CLI equivalent is `inspect-rust-binary PATH`.
Preserve artifact SHA-256, package order, dependency indices, and the section
file range. A missing section is null metadata, not proof the binary has no
dependencies. An omitted package kind stays null. A rustc commit hash is
inferred from a read-only `/rustc/<40-hex>/` path and does not by itself
identify the compiler. See [Rust binaries](https://github.com/morluto/rea/blob/main/docs/rust-binaries.md).
## SQLite snapshots
Use `inspect_sqlite_database` with an explicit local database snapshot for its
+42
View File
@@ -0,0 +1,42 @@
name: Cache npm package downloads
description: Restore npm's download cache and save it only from trusted default-branch events.
outputs:
can-save:
description: Whether this run may update the shared npm download cache.
value: ${{ steps.context.outputs.can-save }}
path:
description: The npm download-cache directory.
value: ${{ steps.context.outputs.path }}
runs:
using: composite
steps:
- id: context
shell: bash
env:
DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
LOCKFILES_HASH: ${{ hashFiles('package-lock.json', 'npm-shrinkwrap.json', '.npmrc') }}
run: |
cache_path="$(npm config get cache)"
runtime_arch="$(node -p 'process.arch')"
can_save=false
if [[ -n "${DEFAULT_BRANCH}" && "${GITHUB_REF}" == "refs/heads/${DEFAULT_BRANCH}" && ( "${GITHUB_EVENT_NAME}" == "push" || "${GITHUB_EVENT_NAME}" == "schedule" || "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ) ]]; then
can_save=true
fi
cache_key="npm-download-${RUNNER_OS}-${runtime_arch}-${LOCKFILES_HASH}"
{
printf 'can-save=%s\n' "${can_save}"
printf 'path=%s\n' "${cache_path}"
printf 'key=%s\n' "${cache_key}"
} >> "${GITHUB_OUTPUT}"
- name: Restore and save npm package downloads
if: steps.context.outputs.can-save == 'true'
uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
path: ${{ steps.context.outputs.path }}
key: ${{ steps.context.outputs.key }}
- name: Restore npm package downloads without saving
if: steps.context.outputs.can-save != 'true'
uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
path: ${{ steps.context.outputs.path }}
key: ${{ steps.context.outputs.key }}
+69 -15
View File
@@ -42,6 +42,7 @@ jobs:
tier: ${{ steps.plan.outputs.tier }}
qualification_run_id: ${{ steps.qualification.outputs.run_id }}
code: ${{ steps.plan.outputs.code }}
reverse_tools: ${{ steps.plan.outputs.reverse_tools }}
sqlite: ${{ steps.plan.outputs.sqlite }}
runtime: ${{ steps.plan.outputs.runtime }}
package: ${{ steps.plan.outputs.package }}
@@ -122,8 +123,19 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- run: npm ci
- name: Restore static task cache
if: needs.changes.outputs.code == 'true'
id: static-cache
uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
path: .turbo/cache/
key: rea-static-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('.nvmrc', '.npmrc', 'package-lock.json') }}-${{ github.sha }}
# Turbo validates each task's inputs after restoring this snapshot.
restore-keys: rea-static-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('.nvmrc', '.npmrc', 'package-lock.json') }}-
- name: Validate workflow syntax and expressions
if: needs.changes.outputs.workflows == 'true'
run: go run github.com/rhysd/actionlint/cmd/actionlint@v1.7.7 -shellcheck= -pyflakes=
@@ -136,6 +148,15 @@ jobs:
run: npm run test:python
- if: needs.changes.outputs.code != 'true'
run: npm run format:check
- name: Save validated static task cache
if: >-
success() && needs.changes.outputs.code == 'true' &&
steps.npm-cache.outputs.can-save == 'true' &&
steps.static-cache.outputs.cache-hit != 'true'
uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
path: .turbo/cache/
key: ${{ steps.static-cache.outputs.cache-primary-key }}
- name: Upload complete static diagnostics
if: always() && needs.changes.outputs.code == 'true'
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
@@ -153,7 +174,9 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
fail-fast: false
# Failed PRs release the remaining matrix slots; qualification retains
# every shard's diagnostics and coverage. Passing PRs run the full suite.
fail-fast: ${{ github.event_name == 'pull_request' && needs.changes.outputs.tier == 'fast' }}
matrix:
shard: [1/6, 2/6, 3/6, 4/6, 5/6, 6/6]
steps:
@@ -161,7 +184,9 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- run: npm ci
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
@@ -187,6 +212,24 @@ jobs:
overwrite: true
retention-days: 7
reverse-tools-quality:
name: Reverse tools coverage and mutation
needs: [changes, static]
if: needs.changes.outputs.reverse_tools == 'true'
runs-on: ubuntu-latest
timeout-minutes: 60
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
cache: npm
- run: npm ci
- name: Run reverse tools tests with coverage
run: npm run test:coverage:reverse-tools
- name: Report reverse tools mutation results
run: npm run test:mutation:reverse-tools
build:
name: Build package
needs: changes
@@ -212,7 +255,9 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- run: npm ci
- name: Reuse portable build outputs across runs
uses: ./.github/actions/portable-build-cache
@@ -286,7 +331,10 @@ jobs:
if: needs.changes.outputs.code == 'true' && success()
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
if: needs.changes.outputs.code == 'true' && success()
id: npm-cache
uses: ./.github/actions/npm-cache
- if: needs.changes.outputs.code == 'true' && success()
run: npm ci
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
@@ -450,7 +498,9 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- name: Verify native runtime identity
env:
EXPECTED_CI_PLATFORM: ${{ matrix.platform }}
@@ -472,11 +522,6 @@ jobs:
- run: npm run verify:windows-native:artifact
- name: Verify NativeAOT diagnostic applicability on this host
run: npm run test:focused -- tests/evaluation/package/nativeAotDiagnostics.test.ts
- name: Resolve npm cache before verifier HOME isolation
id: npm-cache
run: |
cache_path="$(npm config get cache)"
echo "path=${cache_path}" >> "${GITHUB_OUTPUT}"
- run: npm run verify:package
env:
npm_config_cache: ${{ steps.npm-cache.outputs.path }}
@@ -506,7 +551,9 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- run: npm ci
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
@@ -554,7 +601,9 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- run: npm ci
- name: Run the public CLI/MCP reconstruction journey
env:
@@ -583,7 +632,9 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- run: npm ci
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
@@ -703,7 +754,9 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- run: npm ci
- run: npm run docs:check
- name: Generation leaves authored files unchanged
@@ -792,6 +845,7 @@ jobs:
changes,
static,
build,
reverse-tools-quality,
test-shard,
sqlite-runtime,
test,
+3 -1
View File
@@ -23,6 +23,8 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- run: npm ci
- run: npm run docs:build
+3 -1
View File
@@ -32,7 +32,9 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- run: npm ci
- uses: ./.github/actions/portable-build-cache
with:
+3 -1
View File
@@ -25,7 +25,9 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- run: npm ci
- uses: ./.github/actions/portable-build-cache
with:
+74
View File
@@ -0,0 +1,74 @@
name: Real upstream Cutter verification
on:
workflow_dispatch:
repository_dispatch:
types: [real-cutter-upstream]
permissions:
contents: read
jobs:
windows-native-artifact:
name: Build Windows bridge security boundary
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
- name: Install the cross compiler used by the Windows native lane
run: |
sudo apt-get update
sudo apt-get install --no-install-recommends -y g++-mingw-w64-x86-64
- run: npm run build:windows-native
- uses: actions/upload-artifact@v4
with:
name: cutter-windows-native
path: native/windows/build/
if-no-files-found: error
cutter-upstream:
name: Cutter upstream smoke (${{ matrix.platform }})
needs: windows-native-artifact
runs-on: ${{ matrix.runner }}
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
include:
- platform: linux
runner: [self-hosted, cutter-upstream, linux]
- platform: macOS
runner: [self-hosted, cutter-upstream, macOS]
- platform: Windows
runner: [self-hosted, cutter-upstream, Windows]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
cache: npm
- run: npm ci
- if: matrix.platform == 'Windows'
uses: actions/download-artifact@v4
with:
name: cutter-windows-native
path: native/windows/build/
- if: matrix.platform == 'Windows'
run: npm run verify:windows-native:artifact
- if: matrix.platform == 'Windows'
run: npm run build:cached
- if: matrix.platform == 'Windows'
run: npm run verify:windows-native
- name: Verify host and real Cutter bridge
env:
EXPECTED_PLATFORM: ${{ matrix.platform }}
run: npm run verify:cutter
- uses: actions/upload-artifact@v4
if: always()
with:
name: cutter-upstream-${{ matrix.platform }}
path: cutter-smoke.json
if-no-files-found: ignore
retention-days: 30
+3 -1
View File
@@ -26,7 +26,9 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- run: npm ci
- uses: ./.github/actions/portable-build-cache
with:
+3 -1
View File
@@ -48,7 +48,9 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0
with:
go-version: "1.26.1"
+6 -2
View File
@@ -19,7 +19,9 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- run: npm ci
- name: Pack CLI for setup verification
shell: bash
@@ -40,7 +42,9 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- run: npm ci
- name: Install packed CLI in isolation
shell: bash
+3 -1
View File
@@ -19,7 +19,9 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- run: npm ci
- name: Install packed CLI in isolation
shell: bash
@@ -27,7 +27,9 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- run: npm ci
- uses: ./.github/actions/portable-build-cache
with:
+3 -1
View File
@@ -47,7 +47,9 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- run: sudo apt-get update && sudo DEBIAN_FRONTEND=noninteractive apt-get install -y tshark util-linux python3
- run: npm ci
- run: npm run build:cached
+3 -1
View File
@@ -29,7 +29,9 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- run: npm ci
- uses: ./.github/actions/portable-build-cache
with:
+3 -1
View File
@@ -40,7 +40,9 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- run: sudo apt-get update && sudo apt-get install -y sigrok-cli util-linux python3
- run: npm ci
- run: npm run build:cached
@@ -26,7 +26,9 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- name: Use pinned package manager
run: npm install --global npm@11.16.0
- run: npm ci
+4 -2
View File
@@ -21,12 +21,14 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- run: npm ci
- uses: ./.github/actions/portable-build-cache
with:
build_cache_artifact: ${{ inputs.build_cache_artifact }}
- run: npm run verify:browser:runtime
- run: env -u DBUS_SESSION_BUS_ADDRESS npm run verify:browser:runtime
env:
REA_BROWSER_EXECUTABLE: /usr/bin/google-chrome
REA_BROWSER_NO_SANDBOX: "true"
+3 -1
View File
@@ -21,7 +21,9 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- run: npm ci
- uses: ./.github/actions/portable-build-cache
with:
+3 -1
View File
@@ -27,7 +27,9 @@ jobs:
with:
node-version: ${{ matrix.node }}
check-latest: true
cache: npm
- name: Cache npm package downloads
id: npm-cache
uses: ./.github/actions/npm-cache
- run: npm ci
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
+2
View File
@@ -33,6 +33,8 @@ codedb.snapshot
htmlcov/
.coverage
coverage/
.stryker-tmp/
reports/mutation/
.vitest/
.vitest-reports/
test-results.xml
+12
View File
@@ -21,6 +21,12 @@
[Quick start](#quick-start) · [How REA works](#how-rea-works) · [What you can analyze](#what-you-can-analyze) · [Showcases](#showcases) · [FAQ](#faq) · [Documentation](#documentation)
> [!IMPORTANT]
> Get REA from [morluto/rea](https://github.com/morluto/rea),
> [rea.tools](https://rea.tools/), or the [rea-agents npm package](https://www.npmjs.com/package/rea-agents).
> Follow the installation and release links from these official sources. A similar
> repository name or copied README does not establish that a download is official.
<code>npx rea-agents setup</code>
<br />
@@ -155,6 +161,7 @@ Additional tools and host support depend on the target:
| Native binaries | Pseudocode, assembly, strings, symbols, calls and references | Hopper, Ghidra or IDA; [native analysis](https://rea.tools/guides/native/) |
| Offline ELF layout | Sections, segments, original symbols/relocations and static mitigation candidates | Caller-supplied pwntools on Linux x64; [binary diagnostics](docs/binary-diagnostics.md) |
| Go binaries | Embedded compiler version, modules, replacements and build settings | Built-in static ELF/PE/thin Mach-O inspection; no Go installation required |
| Rust binaries | Embedded cargo-auditable crate names, versions, sources and dependency edges | Built-in static ELF/PE/thin Mach-O inspection; [Rust binaries](docs/rust-binaries.md) |
| WASM artifact | Validation, sections, exact import/export WAT forms and decoded WAT | Caller-supplied WABT 1.0.42; `inspect_wasm_artifact` |
| EVM bytecode | Dispatch selectors, byte offsets, inferred arguments and mutability | Local raw/hex carrier on Linux x64; [offline EVM guide](docs/evm-bytecode.md) |
| SQLite databases | Tables, columns, indexes, views, triggers and selected ordinary-table rows | Local database/WAL snapshot; Node.js 24.x >=24.15 or 26+ with native SQLite limits |
@@ -179,6 +186,11 @@ Static JavaScript and .NET inspection read the supplied files without running
the application. Runtime capture runs or interacts with the selected target
using your user permissions; each runtime guide describes its effects.
For offline native-binary inspection, REA also supports caller-supplied GNU
objdump and Rizin. See the [reverse-engineering tools guide](docs/reverse-engineering-tools.md)
for provider setup, CLI commands, and Evidence limitations. REA does not install
or update either provider.
<a id="choosing-a-deep-analysis-provider"></a>
Native formats and host support vary by provider. See
+816
View File
@@ -0,0 +1,816 @@
"""REA's experimental local bridge plugin for Cutter.
Install this file in Cutter's user plugin directory. The bridge is REA-owned
IPC, not an upstream Cutter transport. It binds to loopback and requires a
per-process random token stored in a user-only descriptor file.
"""
from __future__ import annotations
import json
import hashlib
import hmac
import os
import secrets
import socket
import stat
import tempfile
import threading
import time
import uuid
from pathlib import Path
from typing import Any
if os.name == "nt":
import ctypes
from ctypes import wintypes
import cutter
try:
from PySide6.QtCore import QObject, Signal
except ImportError:
from PySide2.QtCore import QObject, Signal
MAX_FRAME_BYTES = 16 * 1024 * 1024
SOCKET_TIMEOUT_SECONDS = 20
AUTH_FRAME_TIMEOUT_SECONDS = 1
MAX_DESCRIPTOR_BYTES = 64 * 1024
MAX_COMPLETION_RECEIPTS = 64
def _windows_api() -> tuple[Any, Any]:
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)
kernel32.GetCurrentProcess.restype = wintypes.HANDLE
kernel32.LocalFree.argtypes = [wintypes.HLOCAL]
kernel32.LocalFree.restype = wintypes.HLOCAL
kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
kernel32.CloseHandle.restype = wintypes.BOOL
kernel32.GetFileAttributesW.argtypes = [wintypes.LPCWSTR]
kernel32.GetFileAttributesW.restype = wintypes.DWORD
kernel32.CreateDirectoryW.argtypes = [wintypes.LPCWSTR, wintypes.LPVOID]
kernel32.CreateDirectoryW.restype = wintypes.BOOL
kernel32.CreateFileW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD,
wintypes.LPVOID, wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE]
kernel32.CreateFileW.restype = wintypes.HANDLE
kernel32.WriteFile.argtypes = [wintypes.HANDLE, wintypes.LPVOID, wintypes.DWORD,
ctypes.POINTER(wintypes.DWORD), wintypes.LPVOID]
kernel32.WriteFile.restype = wintypes.BOOL
kernel32.FlushFileBuffers.argtypes = [wintypes.HANDLE]
kernel32.FlushFileBuffers.restype = wintypes.BOOL
kernel32.MoveFileExW.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.DWORD]
kernel32.MoveFileExW.restype = wintypes.BOOL
kernel32.DeleteFileW.argtypes = [wintypes.LPCWSTR]
kernel32.DeleteFileW.restype = wintypes.BOOL
advapi32.OpenProcessToken.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)]
advapi32.OpenProcessToken.restype = wintypes.BOOL
advapi32.GetTokenInformation.argtypes = [wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID,
wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)]
advapi32.GetTokenInformation.restype = wintypes.BOOL
advapi32.ConvertSidToStringSidW.argtypes = [wintypes.LPVOID, ctypes.POINTER(wintypes.LPWSTR)]
advapi32.ConvertSidToStringSidW.restype = wintypes.BOOL
advapi32.GetNamedSecurityInfoW.argtypes = [wintypes.LPWSTR, ctypes.c_int, wintypes.DWORD,
ctypes.POINTER(wintypes.LPVOID), ctypes.POINTER(wintypes.LPVOID),
ctypes.POINTER(wintypes.LPVOID), ctypes.POINTER(wintypes.LPVOID),
ctypes.POINTER(wintypes.LPVOID)]
advapi32.GetNamedSecurityInfoW.restype = wintypes.DWORD
advapi32.GetSecurityDescriptorControl.argtypes = [wintypes.LPVOID, ctypes.POINTER(wintypes.WORD),
ctypes.POINTER(wintypes.DWORD)]
advapi32.GetSecurityDescriptorControl.restype = wintypes.BOOL
advapi32.EqualSid.argtypes = [wintypes.LPVOID, wintypes.LPVOID]
advapi32.EqualSid.restype = wintypes.BOOL
advapi32.GetAclInformation.argtypes = [wintypes.LPVOID, wintypes.LPVOID, wintypes.DWORD, ctypes.c_int]
advapi32.GetAclInformation.restype = wintypes.BOOL
advapi32.GetAce.argtypes = [wintypes.LPVOID, wintypes.DWORD, ctypes.POINTER(wintypes.LPVOID)]
advapi32.GetAce.restype = wintypes.BOOL
advapi32.IsValidSid.argtypes = [wintypes.LPVOID]
advapi32.IsValidSid.restype = wintypes.BOOL
advapi32.GetLengthSid.argtypes = [wintypes.LPVOID]
advapi32.GetLengthSid.restype = wintypes.DWORD
advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [
wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(wintypes.LPVOID), ctypes.POINTER(wintypes.DWORD),
]
advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW.restype = wintypes.BOOL
return kernel32, advapi32
def _windows_user_sid_text() -> str:
kernel32, advapi32 = _windows_api()
token = wintypes.HANDLE()
if not advapi32.OpenProcessToken(kernel32.GetCurrentProcess(), 0x0008, ctypes.byref(token)):
raise ctypes.WinError(ctypes.get_last_error())
try:
required = wintypes.DWORD()
advapi32.GetTokenInformation(token, 1, None, 0, ctypes.byref(required))
if required.value == 0:
raise ctypes.WinError(ctypes.get_last_error())
buffer = ctypes.create_string_buffer(required.value)
if not advapi32.GetTokenInformation(token, 1, buffer, required, ctypes.byref(required)):
raise ctypes.WinError(ctypes.get_last_error())
class SID_AND_ATTRIBUTES(ctypes.Structure):
_fields_ = [("Sid", wintypes.LPVOID), ("Attributes", wintypes.DWORD)]
class TOKEN_USER(ctypes.Structure):
_fields_ = [("User", SID_AND_ATTRIBUTES)]
sid = ctypes.cast(buffer, ctypes.POINTER(TOKEN_USER)).contents.User.Sid
text = wintypes.LPWSTR()
if not advapi32.ConvertSidToStringSidW(sid, ctypes.byref(text)):
raise ctypes.WinError(ctypes.get_last_error())
try:
return text.value
finally:
kernel32.LocalFree(text)
finally:
kernel32.CloseHandle(token)
def _verify_windows_private_path(path: Path, directory: bool) -> None:
kernel32, advapi32 = _windows_api()
attributes = kernel32.GetFileAttributesW(str(path))
if attributes == 0xFFFFFFFF:
raise ctypes.WinError(ctypes.get_last_error())
if attributes & 0x400 or bool(attributes & 0x10) != directory:
raise RuntimeError("Cutter bridge path is a reparse point or has the wrong object type")
class ACL_SIZE_INFORMATION(ctypes.Structure):
_fields_ = [("AceCount", wintypes.DWORD), ("AclBytesInUse", wintypes.DWORD), ("AclBytesFree", wintypes.DWORD)]
class ACE_HEADER(ctypes.Structure):
_fields_ = [("AceType", wintypes.BYTE), ("AceFlags", wintypes.BYTE), ("AceSize", wintypes.WORD)]
class SID_HEADER(ctypes.Structure):
_fields_ = [("Revision", wintypes.BYTE), ("SubAuthorityCount", wintypes.BYTE),
("IdentifierAuthority", wintypes.BYTE * 6)]
class ACCESS_ALLOWED_ACE(ctypes.Structure):
_fields_ = [("Header", ACE_HEADER), ("Mask", wintypes.DWORD), ("SidStart", wintypes.DWORD)]
owner = wintypes.LPVOID()
dacl = wintypes.LPVOID()
descriptor = wintypes.LPVOID()
result = advapi32.GetNamedSecurityInfoW(
str(path), 1, 0x1 | 0x4, ctypes.byref(owner), None, ctypes.byref(dacl), None, ctypes.byref(descriptor),
)
if result != 0:
raise ctypes.WinError(result)
try:
control = wintypes.WORD()
revision = wintypes.DWORD()
if not advapi32.GetSecurityDescriptorControl(descriptor, ctypes.byref(control), ctypes.byref(revision)):
raise ctypes.WinError(ctypes.get_last_error())
if not control.value & 0x1000 or not dacl:
raise RuntimeError("Cutter bridge ACL must be present and protected from inheritance")
token = wintypes.HANDLE()
if not advapi32.OpenProcessToken(kernel32.GetCurrentProcess(), 0x0008, ctypes.byref(token)):
raise ctypes.WinError(ctypes.get_last_error())
try:
required = wintypes.DWORD()
advapi32.GetTokenInformation(token, 1, None, 0, ctypes.byref(required))
token_user = ctypes.create_string_buffer(required.value)
if not advapi32.GetTokenInformation(token, 1, token_user, required, ctypes.byref(required)):
raise ctypes.WinError(ctypes.get_last_error())
class SID_AND_ATTRIBUTES(ctypes.Structure):
_fields_ = [("Sid", wintypes.LPVOID), ("Attributes", wintypes.DWORD)]
class TOKEN_USER(ctypes.Structure):
_fields_ = [("User", SID_AND_ATTRIBUTES)]
current_sid = ctypes.cast(token_user, ctypes.POINTER(TOKEN_USER)).contents.User.Sid
if not advapi32.EqualSid(owner, current_sid):
raise RuntimeError("Cutter bridge path owner does not match the current user")
finally:
kernel32.CloseHandle(token)
info = ACL_SIZE_INFORMATION()
if not advapi32.GetAclInformation(dacl, ctypes.byref(info), ctypes.sizeof(info), 2) or info.AceCount != 2:
raise RuntimeError("Cutter bridge ACL must allow only the current user and SYSTEM")
expected_user = _windows_user_sid_text()
user_allowed = False
system_allowed = False
for index in range(info.AceCount):
ace_pointer = wintypes.LPVOID()
if not advapi32.GetAce(dacl, index, ctypes.byref(ace_pointer)):
raise ctypes.WinError(ctypes.get_last_error())
header = ctypes.cast(ace_pointer, ctypes.POINTER(ACE_HEADER)).contents
if header.AceType != 0 or header.AceSize < ctypes.sizeof(ACE_HEADER) + ctypes.sizeof(wintypes.DWORD) + ctypes.sizeof(SID_HEADER):
raise RuntimeError("Cutter bridge ACL contains a malformed or unsupported ACE")
ace_address = ctypes.cast(ace_pointer, ctypes.c_void_p).value
if ace_address is None:
raise RuntimeError("Cutter bridge ACL returned a null ACE")
sid_pointer = ctypes.c_void_p(ace_address + ctypes.sizeof(ACE_HEADER) + ctypes.sizeof(wintypes.DWORD))
sid_header = ctypes.cast(sid_pointer, ctypes.POINTER(SID_HEADER)).contents
sid_size = ctypes.sizeof(SID_HEADER) + sid_header.SubAuthorityCount * ctypes.sizeof(wintypes.DWORD)
if sid_size > header.AceSize - ctypes.sizeof(ACE_HEADER) - ctypes.sizeof(wintypes.DWORD) or not advapi32.IsValidSid(sid_pointer) or advapi32.GetLengthSid(sid_pointer) != sid_size:
raise RuntimeError("Cutter bridge ACL contains an invalid SID")
ace = ctypes.cast(ace_pointer, ctypes.POINTER(ACCESS_ALLOWED_ACE)).contents
sid_text = wintypes.LPWSTR()
if ace.Mask != 0x001F01FF or ace.Header.AceFlags != 0x03:
raise RuntimeError("Cutter bridge ACL contains an unsupported ACE")
if not advapi32.ConvertSidToStringSidW(sid_pointer, ctypes.byref(sid_text)):
raise ctypes.WinError(ctypes.get_last_error())
try:
if sid_text.value == expected_user:
user_allowed = True
elif sid_text.value == "S-1-5-18":
system_allowed = True
else:
raise RuntimeError("Cutter bridge ACL allows an unrelated principal")
finally:
kernel32.LocalFree(sid_text)
if not user_allowed or not system_allowed:
raise RuntimeError("Cutter bridge ACL must allow only the current user and SYSTEM")
finally:
kernel32.LocalFree(descriptor)
def _windows_security_attributes() -> tuple[Any, Any]:
kernel32, advapi32 = _windows_api()
sid = _windows_user_sid_text()
sddl = f"O:{sid}G:{sid}D:P(A;OICI;FA;;;{sid})(A;OICI;FA;;;SY)"
descriptor = wintypes.LPVOID()
if not advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl, 1, ctypes.byref(descriptor), None):
raise ctypes.WinError(ctypes.get_last_error())
class SECURITY_ATTRIBUTES(ctypes.Structure):
_fields_ = [("nLength", wintypes.DWORD), ("lpSecurityDescriptor", wintypes.LPVOID), ("bInheritHandle", wintypes.BOOL)]
attributes = SECURITY_ATTRIBUTES(ctypes.sizeof(SECURITY_ATTRIBUTES), descriptor, False)
return kernel32, (descriptor, attributes)
def _ensure_windows_bridge_directory(directory: Path) -> None:
directory.parent.mkdir(parents=True, exist_ok=True)
if not directory.exists():
kernel32, (descriptor, attributes) = _windows_security_attributes()
try:
if not kernel32.CreateDirectoryW(str(directory), ctypes.byref(attributes)):
error = ctypes.get_last_error()
if error != 183:
raise ctypes.WinError(error)
finally:
kernel32.LocalFree(descriptor)
_verify_windows_private_path(directory, True)
def _ensure_posix_bridge_directory(directory: Path) -> None:
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
if not hasattr(os, "O_NOFOLLOW") or not hasattr(os, "O_DIRECTORY"):
raise RuntimeError("Cutter bridge directory requires no-follow directory handles")
descriptor = os.open(directory, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
directory_info = os.fstat(descriptor)
if directory_info.st_uid != os.getuid():
raise RuntimeError("Cutter bridge directory must be owned by the current user")
os.fchmod(descriptor, 0o700)
directory_info = os.fstat(descriptor)
if stat.S_IMODE(directory_info.st_mode) != 0o700:
raise RuntimeError("Cutter bridge directory must have mode 0700")
finally:
os.close(descriptor)
def _write_windows_descriptor(directory: Path, destination: Path, payload: bytes) -> None:
if len(payload) > MAX_DESCRIPTOR_BYTES:
raise RuntimeError("Cutter bridge descriptor exceeds its byte limit")
kernel32, (security_descriptor, attributes) = _windows_security_attributes()
temporary = directory / f".{destination.name}.{uuid.uuid4().hex}.tmp"
handle = wintypes.HANDLE()
try:
handle = kernel32.CreateFileW(str(temporary), 0x40000000 | 0x00020000 | 0x00040000,
0x1 | 0x2 | 0x4, ctypes.byref(attributes), 1, 0x80, None)
if handle == wintypes.HANDLE(-1).value:
raise ctypes.WinError(ctypes.get_last_error())
_verify_windows_private_path(temporary, False)
if payload:
data = ctypes.create_string_buffer(payload)
written = wintypes.DWORD()
if not kernel32.WriteFile(handle, data, len(payload), ctypes.byref(written), None) or written.value != len(payload):
raise ctypes.WinError(ctypes.get_last_error())
if not kernel32.FlushFileBuffers(handle):
raise ctypes.WinError(ctypes.get_last_error())
kernel32.CloseHandle(handle)
handle = wintypes.HANDLE()
if not kernel32.MoveFileExW(str(temporary), str(destination), 0x1 | 0x8):
raise ctypes.WinError(ctypes.get_last_error())
finally:
if handle and handle != wintypes.HANDLE(-1).value:
kernel32.CloseHandle(handle)
kernel32.DeleteFileW(str(temporary))
kernel32.LocalFree(security_descriptor)
def _bridge_directory() -> Path:
configured = os.environ.get("REA_CUTTER_BRIDGE_DIR")
if configured:
return Path(configured).expanduser()
local_app_data = os.environ.get("LOCALAPPDATA")
if os.name == "nt" and local_app_data:
return Path(local_app_data) / "REA" / "CutterBridge"
return Path.home() / ".cache" / "rea" / "cutter-bridge"
class _RequestDispatcher(QObject):
dispatch = Signal(object, object)
def __init__(self) -> None:
super().__init__()
self.dispatch.connect(self._handle)
self.generation = 0
self.completed_commands: dict[str, str] = {}
self._receipt_lock = threading.Lock()
self.current_file = self._read_current_file()
try:
self.cutter_version = str(cutter.core().getVersionInformation())
except Exception:
self.cutter_version = None
@staticmethod
def _read_current_file() -> str | None:
try:
value = cutter.core().currentlyOpenFile()
return str(value) if value else None
except Exception:
return None
def _handle(self, request: dict[str, Any], reply: dict[str, Any]) -> None:
kind = request.get("kind")
request_id = request.get("request_id")
if kind in ("command", "ack"):
try:
valid_request_id = (
isinstance(request_id, str)
and str(uuid.UUID(request_id)) == request_id.lower()
)
except (ValueError, AttributeError):
valid_request_id = False
if not valid_request_id:
reply.update({
"ok": False,
"error": "invalid-command-request-id",
"execution_state": "not_started",
})
request["_event"].set()
return
if kind == "ack":
with self._receipt_lock:
acknowledged = self.completed_commands.pop(request_id, None) is not None
reply.update({"ok": True, "acknowledged": acknowledged})
request["_event"].set()
return
if request["_cancelled"].is_set():
reply.update({
"ok": False,
"error": "request-cancelled-before-execution",
"execution_state": "not_started",
})
if kind == "command":
self._record_command_completion(request_id, "not_started")
request["_event"].set()
return
self._refresh_document_identity()
if kind == "status":
with self._receipt_lock:
completed_commands = [
{"request_id": receipt_id, "execution_state": state}
for receipt_id, state in self.completed_commands.items()
]
reply.update({
"ok": True,
"session_id": request.get("session_id"),
"current_file": self.current_file,
"document_generation": self.generation,
"cutter_version": self.cutter_version,
"identity_status": "partial",
"completed_commands": completed_commands,
})
request["_event"].set()
return
if kind != "command":
reply.update({"ok": False, "error": "unsupported-request-kind"})
request["_event"].set()
return
if request.get("expected_generation") != self.generation:
reply.update({
"ok": False,
"error": "active-document-generation-changed",
"execution_state": "not_started",
})
self._record_command_completion(request_id, "not_started")
request["_event"].set()
return
command = request.get("command")
if not isinstance(command, str) or not command.strip():
reply.update({
"ok": False,
"error": "invalid-command",
"execution_state": "not_started",
})
self._record_command_completion(request_id, "not_started")
request["_event"].set()
return
reply["execution_state"] = "running"
try:
output = cutter.cmdj(command) if request.get("json") is True else cutter.cmd(command)
command_error = None
except Exception as error:
output = None
command_error = str(error)
self._refresh_document_identity()
if command_error is None:
reply.update({
"ok": True,
"output": output,
"current_file": self.current_file,
"document_generation": self.generation,
"cutter_version": self.cutter_version,
"identity_status": "partial",
"execution_state": "complete",
})
self._record_command_completion(request_id, "complete")
else:
reply.update({
"ok": False,
"error": command_error,
"current_file": self.current_file,
"document_generation": self.generation,
"cutter_version": self.cutter_version,
"identity_status": "partial",
"execution_state": "unknown",
"message": "The command raised an exception; it may have produced partial effects. Do not retry automatically.",
})
self._record_command_completion(request_id, "failed")
request["_event"].set()
def _record_command_completion(
self, request_id: str, execution_state: str
) -> None:
with self._receipt_lock:
if request_id in self.completed_commands or len(self.completed_commands) < MAX_COMPLETION_RECEIPTS:
self.completed_commands[request_id] = execution_state
def can_accept_command(self) -> bool:
with self._receipt_lock:
return len(self.completed_commands) < MAX_COMPLETION_RECEIPTS
def _refresh_document_identity(self) -> None:
current_file = self._read_current_file()
if current_file != self.current_file:
self.current_file = current_file
self.generation += 1
class _BridgeServer(threading.Thread):
def __init__(self, dispatcher: _RequestDispatcher) -> None:
super().__init__(name="rea-cutter-bridge", daemon=True)
self.dispatcher = dispatcher
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server.bind(("127.0.0.1", 0))
self.server.listen(8)
self.server.settimeout(0.5)
self.port = self.server.getsockname()[1]
self.session_id = str(uuid.uuid4())
self.token = secrets.token_urlsafe(32)
self.poisoned = False
self.connection_ordinal = 0
self.directory = _bridge_directory()
self.descriptor = self.directory / f"cutter-{os.getpid()}-{self.session_id}.json"
def publish(self) -> None:
if os.name == "nt":
_ensure_windows_bridge_directory(self.directory)
else:
_ensure_posix_bridge_directory(self.directory)
if os.name == "nt" and (self.directory.is_symlink() or not self.directory.is_dir()):
raise RuntimeError("Cutter bridge directory must be a real directory")
payload = {
"session_id": self.session_id,
"pid": os.getpid(),
"host": "127.0.0.1",
"port": self.port,
"token": self.token,
"document_generation": self.dispatcher.generation,
"current_file": self.dispatcher.current_file,
"cutter_version": self.dispatcher.cutter_version,
"identity_status": "partial",
}
if os.name == "nt":
_write_windows_descriptor(self.directory, self.descriptor, json.dumps(payload).encode("utf-8"))
return
descriptor, temporary_path = tempfile.mkstemp(prefix=f".{self.descriptor.name}.", dir=self.directory)
try:
os.fchmod(descriptor, 0o600)
descriptor_info = os.fstat(descriptor)
if descriptor_info.st_uid != os.getuid() or stat.S_IMODE(descriptor_info.st_mode) & 0o077:
raise RuntimeError("Cutter bridge descriptor must be owned by the current user with mode 0600")
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
stream.write(json.dumps(payload))
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary_path, self.descriptor)
except Exception:
try:
os.close(descriptor)
except OSError:
pass
try:
os.unlink(temporary_path)
except OSError:
pass
raise
def run(self) -> None:
try:
self.publish()
except Exception:
self.server.close()
return
while True:
try:
connection, _ = self.server.accept()
except socket.timeout:
if getattr(self, "stopping", False):
break
continue
except OSError:
break
self.connection_ordinal += 1
connection_ordinal = self.connection_ordinal
with connection:
connection.settimeout(AUTH_FRAME_TIMEOUT_SECONDS)
authenticated = False
try:
hello = self._receive_frame(connection)
if not isinstance(hello, dict) or hello.get("kind") != "rea-auth-v2" or not isinstance(hello.get("nonce"), str) or len(hello["nonce"]) != 64:
self._send(connection, {"ok": False, "error": "authentication-failed"})
continue
client_nonce = hello["nonce"]
server_nonce = f"{connection_ordinal:016x}{secrets.token_hex(24)}"
server_proof = hmac.new(self.token.encode(), f"rea-cutter-server-v2:{self.session_id}:{client_nonce}:{server_nonce}".encode(), hashlib.sha256).hexdigest()
self._send(connection, {"session_id": self.session_id, "nonce": server_nonce, "proof": server_proof})
authenticated_frame = self._receive_frame(connection)
request_bytes = authenticated_frame.get("request") if isinstance(authenticated_frame, dict) else None
expected_proof = hmac.new(self.token.encode(), f"rea-cutter-client-v2:{self.session_id}:{client_nonce}:{server_nonce}:{request_bytes}".encode(), hashlib.sha256).hexdigest()
if not isinstance(request_bytes, str) or not isinstance(authenticated_frame.get("proof"), str) or not hmac.compare_digest(authenticated_frame["proof"], expected_proof):
self._send(connection, {"ok": False, "error": "authentication-failed"})
continue
request = json.loads(request_bytes)
if not isinstance(request, dict) or request.get("session_id") != self.session_id:
self._send(connection, {"ok": False, "error": "authentication-failed"})
continue
authenticated = True
connection.settimeout(SOCKET_TIMEOUT_SECONDS)
if self.poisoned and request.get("kind") not in ("status", "ack"):
self._send_authenticated(connection, {
"ok": False,
"error": "session-poisoned-after-ui-timeout",
"execution_state": "not_started",
}, client_nonce, server_nonce)
continue
if (
request.get("kind") == "command"
and not self.dispatcher.can_accept_command()
):
self._send_authenticated(connection, {
"ok": False,
"error": "completion-receipt-capacity-exceeded",
"execution_state": "not_started",
}, client_nonce, server_nonce)
continue
request["session_id"] = self.session_id
event = threading.Event()
cancelled = threading.Event()
reply: dict[str, Any] = {}
request["_event"] = event
request["_cancelled"] = cancelled
self.dispatcher.dispatch.emit(request, reply)
if not event.wait(SOCKET_TIMEOUT_SECONDS):
cancelled.set()
self.poisoned = True
self._send_authenticated(connection, {
"ok": False,
"error": "ui-thread-request-timeout",
"execution_state": "unknown",
"message": "The UI operation may still complete after this timeout; restart Cutter before issuing further commands.",
}, client_nonce, server_nonce)
else:
if request.get("kind") == "status" and reply.get("ok") is True:
reply["completed_connection"] = f"{connection_ordinal - 1:016x}"
self._send_authenticated(connection, reply, client_nonce, server_nonce)
except socket.timeout:
if authenticated:
self._send_authenticated(connection, {
"ok": False,
"error": "request-timeout",
"execution_state": "unknown",
"message": "The command may have produced partial or persistent effects. Do not retry automatically.",
}, client_nonce, server_nonce)
except Exception as error:
self._send(connection, {"ok": False, "error": str(error)})
self.server.close()
try:
self.descriptor.unlink(missing_ok=True)
except OSError:
pass
@staticmethod
def _receive_frame(connection: socket.socket) -> dict[str, Any]:
data = bytearray()
deadline = time.monotonic() + AUTH_FRAME_TIMEOUT_SECONDS
while b"\n" not in data:
if len(data) >= MAX_FRAME_BYTES:
raise ValueError("frame-limit-exceeded")
remaining = deadline - time.monotonic()
if remaining <= 0:
raise socket.timeout("authentication frame timed out")
connection.settimeout(remaining)
part = connection.recv(min(65536, MAX_FRAME_BYTES + 1 - len(data)))
if not part:
raise ValueError("incomplete authentication frame")
data.extend(part)
line, remainder = bytes(data).split(b"\n", 1)
if len(line) > MAX_FRAME_BYTES or remainder:
raise ValueError("invalid framed request")
value = json.loads(line)
return value if isinstance(value, dict) else {}
def _send_authenticated(self, connection: socket.socket, value: dict[str, Any], client_nonce: str, server_nonce: str) -> None:
encoded = self._encode_authenticated_response(value, client_nonce, server_nonce)
if encoded is None:
value = self._truncated_response(value)
encoded = self._encode_authenticated_response(value, client_nonce, server_nonce)
if encoded is None:
# This fixed-size fallback is checked through the same signed framing path.
value = {
"ok": False,
"error": "response-limit-exceeded",
"execution_state": value.get("execution_state", "unknown"),
"output": None,
"output_truncated": True,
"message": "The result exceeded the bridge frame limit; command completion state is preserved.",
}
encoded = self._encode_authenticated_response(value, client_nonce, server_nonce)
if encoded is None:
return
try:
connection.sendall(encoded)
except OSError:
pass
def _encode_authenticated_response(self, value: dict[str, Any], client_nonce: str, server_nonce: str) -> bytes | None:
if not _within_response_limit(value):
return None
prefix = b'{"response":"'
suffix = b'","proof":"' + (b"0" * 64) + b'"}\n'
frame_size = len(prefix) + len(suffix)
response_parts: list[bytes] = []
escaped_parts: list[bytes] = []
for fragment in json.JSONEncoder(ensure_ascii=False, separators=(",", ":")).iterencode(value):
raw = fragment.encode("utf-8")
escaped = json.dumps(fragment, ensure_ascii=False)[1:-1].encode("utf-8")
frame_size += len(escaped)
if frame_size > MAX_FRAME_BYTES:
return None
response_parts.append(raw)
escaped_parts.append(escaped)
proof = hmac.new(self.token.encode(), digestmod=hashlib.sha256)
proof.update(f"rea-cutter-response-v2:{self.session_id}:{client_nonce}:{server_nonce}:".encode())
for part in response_parts:
proof.update(part)
return prefix + b"".join(escaped_parts) + b'","proof":"' + proof.hexdigest().encode() + b'"}\n'
@staticmethod
def _truncated_response(value: dict[str, Any]) -> dict[str, Any]:
response: dict[str, Any] = {
"ok": value.get("ok") is True,
"output": None,
"execution_state": value.get("execution_state", "unknown"),
"output_truncated": True,
"message": "The command result exceeded the bridge frame limit; completion state is preserved and output was omitted.",
}
for key in ("current_file", "document_generation", "cutter_version", "identity_status"):
if key in value:
response[key] = value[key]
if value.get("ok") is not True and isinstance(value.get("error"), str):
response["error"] = value["error"]
return response
@staticmethod
def _send(connection: socket.socket, value: dict[str, Any]) -> None:
if not _within_response_limit(value):
value = {
"ok": False,
"error": "response-limit-exceeded",
"execution_state": value.get("execution_state", "unknown"),
"output_truncated": True,
"message": "The command completed or may have completed, but its result exceeded the bridge response limit. Do not retry automatically.",
}
parts: list[bytes] = []
encoded_size = 0
for part in json.JSONEncoder(ensure_ascii=False).iterencode(value):
encoded_part = part.encode("utf-8")
encoded_size += len(encoded_part)
if encoded_size > MAX_FRAME_BYTES:
fallback = {
"ok": False,
"error": "response-limit-exceeded",
"execution_state": value.get("execution_state", "unknown"),
"output_truncated": True,
"message": "The command completed or may have completed, but its result exceeded the bridge response limit. Do not retry automatically.",
}
parts = [json.dumps(fallback, separators=(",", ":")).encode("utf-8")]
break
parts.append(encoded_part)
encoded = b"".join(parts)
try:
connection.sendall(encoded + b"\n")
except OSError:
# A disconnected caller must not terminate the bridge thread or
# prevent later commands from being served.
pass
def stop(self) -> None:
self.stopping = True
try:
self.server.close()
except OSError:
pass
class ReaCutterPlugin(cutter.CutterPlugin):
name = "REA Local Bridge"
description = "Local REA analysis bridge for the active Cutter session"
version = "1.0"
author = "REA"
def __init__(self) -> None:
super().__init__()
self._dispatcher: _RequestDispatcher | None = None
self._bridge: _BridgeServer | None = None
def setupPlugin(self) -> None:
return
def setupInterface(self, main: Any) -> None:
self._dispatcher = _RequestDispatcher()
self._bridge = _BridgeServer(self._dispatcher)
self._bridge.start()
def terminate(self) -> None:
if self._bridge is not None:
self._bridge.stop()
self._bridge.join(timeout=2)
self._bridge = None
self._dispatcher = None
def create_cutter_plugin() -> ReaCutterPlugin:
return ReaCutterPlugin()
def _within_response_limit(value: Any) -> bool:
pending = [value]
seen: set[int] = set()
size = 0
while pending:
current = pending.pop()
if isinstance(current, str):
size += 2
if current.isascii():
size += len(current)
size += current.count('"') + current.count("\\")
size += sum(5 for character in current if ord(character) < 0x20)
else:
size += 4 * len(current)
size += current.count('"') + current.count("\\")
size += sum(5 for character in current if ord(character) < 0x20)
elif isinstance(current, dict):
identity = id(current)
if identity in seen:
return False
seen.add(identity)
size += 2 + 4 * len(current)
if size > MAX_FRAME_BYTES:
return False
pending.extend(current.keys())
pending.extend(current.values())
elif isinstance(current, (list, tuple)):
identity = id(current)
if identity in seen:
return False
seen.add(identity)
size += 2 + 2 * len(current)
if size > MAX_FRAME_BYTES:
return False
pending.extend(current)
else:
size += 16
if size > MAX_FRAME_BYTES:
return False
return True
+1
View File
@@ -29,6 +29,7 @@ export default defineConfig({
items: [
{ text: "Native binaries", link: "/native-investigation" },
{ text: "Go build metadata", link: "/go-binaries" },
{ text: "Rust dependencies", link: "/rust-binaries" },
{
text: "JavaScript and Electron",
link: "/javascript-artifact-reconstruction",
+13 -1
View File
@@ -38,6 +38,10 @@ graph TD
JS_CODEC["src/javascript/sourceMaps/<br/>pinned upstream map codec<br/>owned heap-limited Node process, complete point evidence"]
INSPECTOR["src/inspector/<br/>passive V8 Inspector discovery and capture<br/>script and target locations"]
DOTNET["src/dotnet/<br/>Managed static metadata provider<br/>PE/CLI metadata inventory, members, IL"]
OBJDUMP["src/objdump/<br/>GNU objdump command profile"]
RIZIN["src/rizin/<br/>Static command profile and persistent debugger sessions"]
GDB["src/gdb/<br/>Persistent GDB/MI sessions<br/>owned process lifecycle and target state"]
FIRMWARE["src/firmware/<br/>Binwalk / Unblob adapters<br/>owned processes, report normalization, private extraction"]
ANDROID["src/android/<br/>Static APK adapter<br/>owned SDK stdio, pinned headless JADX, normalization"]
REFERENCE["src/reference/<br/>Filesystem reference-source reader<br/>bounded traversal, validation, errors"]
@@ -50,7 +54,7 @@ graph TD
end
subgraph "Contracts Layer"
CONTRACTS["src/contracts/<br/>Caller-visible schemas for analysis, managed, browser, Electron, application, and session tools"]
CONTRACTS["src/contracts/<br/>Caller-visible schemas for analysis, reverse engineering, managed, browser, Electron, application, and session tools"]
ERRORS["src/contracts/errorSchemas.ts<br/>Shared analysis error schemas<br/>CLI diagnostics, generated error catalog"]
end
@@ -122,6 +126,14 @@ graph TD
INSPECTOR --> DOMAIN
APP --> DOTNET
DOTNET --> DOMAIN
COMPOSITION --> OBJDUMP
OBJDUMP --> DOMAIN
COMPOSITION --> RIZIN
RIZIN --> DOMAIN
CLI --> GDB
SERVER --> GDB
GDB --> PROCESS
GDB --> DOMAIN
HOPPER --> HOPPER_BRIDGE
GHIDRA --> GHIDRA_BRIDGE
HOPPER --> PROCESS
+1
View File
@@ -243,6 +243,7 @@ REA retains local observation data and removes only URL userinfo credentials, ex
- Console observations with a stack source retain call type, argument types, timestamp, and source location. When console text capture is selected, already-delivered primitive values are retained verbatim; objects, getters, and remote properties are never expanded.
- WebSocket observations retain direction, opcode, and payload byte length. When shape capture is selected, text frames are classified as text or complete value-free JSON shape; binary bytes, hashes, prefixes, and raw frames are never retained.
- Storage observations always redact values. Key names, IndexedDB names, and cache names require `include_storage_keys`; stable content fingerprints require the additional `include_storage_fingerprints` selection. Cookie fingerprints cover cookies applicable to the current main-frame URL, including its path, rather than every cookie path on that origin. Other storage remains scoped to the origin. Cache bodies above 64 KiB and partial IndexedDB remote objects make fingerprint coverage incomplete, so identical observations remain `unknown`.
- Unavailable or malformed storage inventories mark `storage_keys` unavailable, even without fingerprints. Comparisons suppress inferred key additions and removals while preserving modifications proven by complete fingerprints on both sides. Previously exported captures are not retroactively corrected; recapture them to obtain these coverage markers.
- Script metadata is included only when CDP supplies a URL on an allowed origin. Stable keys exclude transient CDP script IDs, and exact transient raw URLs are used only during script/resource reconciliation. URL-less scripts are excluded because their origin cannot be established. When CDP supplies an execution-context association, the accepted script retains its authorized frame ID for later attribution. Script metadata admission bounds retained identity and source-map strings to 8 MiB and 50,000 records. When a source-map URL cannot fit, the script identity remains and source-map coverage reports `resource_budget_exhausted`; rejected script observations are counted without retaining their IDs. Source content is omitted unless explicitly requested and is returned inline as a self-verifying artifact with its SHA-256 digest.
Frames, resources, scripts, events, and workers outside the selected origin scope are excluded. An explicit `allowed_origins` list can include additional origins; excluded target details are counted without being exposed.
+12
View File
@@ -83,6 +83,18 @@ The shared CLI/MCP workflow reports compiler version, modules, replacements,
build settings, original bytes and SHA-256. See [Go binaries](go-binaries.md)
for supported containers and absent or malformed metadata.
Inspect an embedded cargo-auditable Rust dependency list without installing
Rust or configuring a disassembler:
```bash
rea inspect-rust-binary /absolute/path/to/program --json
```
The same workflow reports package names, versions, sources, the root package,
dependency edges, and the section's file range. A missing `.dep-v0` section is
null metadata, not proof that the binary has no dependencies. See
[Rust binaries](rust-binaries.md).
Configure [Hopper or Ghidra](installation.md#hopper), or the
[IDA adapter](ida-provider.md), before analyzing a native target. Substitute
your target, search text and function name or address in these examples:
+2 -2
View File
@@ -6,8 +6,8 @@ For remote devices, pass a host with an optional port (`host[:port]`; bracket IP
MCP exposes `list_frida_devices`, `list_frida_processes`, `start_frida_session`, `load_frida_script`, `resume_frida_session`, `unload_frida_script`, `frida_session_status`, and `close_frida_session`. A spawned process starts paused so scripts can load first. Closing unloads session scripts and detaches. If a spawn remains paused, REA resumes it only after script cleanup or session detach confirms the instrumentation is released; if both cleanup paths fail, the target stays paused and the cleanup error is retained. REA never kills the target. MCP sessions end with the server process. The one-shot CLI command `instrument-with-frida` accepts one inline script or script file, observes messages for a bounded duration, and returns Evidence with the source hash and captured messages.
Failed startup cleanup retains acquired Frida handles, including a paused spawn that has not attached, for later cleanup retries. Its remote connection stays leased until session detach and target resume complete. CLI commands await provider cleanup before returning; MCP retains these resources for cleanup when its server closes. A failed cleanup remains reported rather than treating an unregistered session as fully released.
Failed startup cleanup retains acquired Frida handles, including a paused spawn that has not attached, for later cleanup retries. Its remote connection stays leased until session detach and target resume complete. CLI commands await provider cleanup before returning; MCP retains these resources for cleanup when its server closes. Server shutdown stops admitting new Frida operations and waits for admitted startup, discovery, and queued work before releasing their resources. A failed cleanup remains reported and can be retried by closing the server again, rather than treating an unregistered session as fully released.
Frida scripts execute inside the selected target with that process's memory, filesystem, and network authority. Message capture is bounded to 16 MiB and reports truncation. Script source is not stored in Evidence; its selected path and SHA-256 digest are. Evidence retains non-authentication target selection such as device or endpoint, mode, program or PID, and spawn arguments. Authentication values remain excluded. Results report the observed session and messages, while unsupported platform metadata remains unknown. A request cancelled before a Frida operation starts has no provider effects. If cancellation arrives during a native Frida call, REA waits for that call to return, then closes any session it created and returns the observed session as a partial observation. Cancellation Evidence separately reports whether a target resume was observed, whether instrumentation cleanup completed, and that final target liveness remains unknown. REA does not kill the target. Remote discovery retains its observations and reports a separate cleanup error if the temporary connection cannot be removed.
Frida scripts execute inside the selected target with that process's memory, filesystem, and network authority. Message capture is bounded to 16 MiB and reports truncation. Script source is not stored in Evidence; its selected path and SHA-256 digest are. Evidence retains non-authentication target selection such as device or endpoint, mode, program or PID, and spawn arguments. Authentication values remain excluded. Results report the observed session and messages, while unsupported platform metadata remains unknown. A request cancelled before a Frida operation starts has no provider effects. If cancellation arrives during a native Frida call, REA waits for that call to return, then closes any session it created and returns the observed session as a partial observation. A cancelled script load on an existing session releases only its new script before queued operations can run; the session and previously loaded scripts remain available. Once the provider commits a successful load, later request cancellation does not unload that script; use `unload_frida_script` to release it. If script cleanup fails, the script remains owned and a paused target cannot resume until the pending instrumentation is released. Queued script loads, resumes, and unloads check cancellation before dispatching native effects. Cancellation Evidence separately reports whether a target resume was observed, whether instrumentation cleanup completed, and that final target liveness remains unknown. REA does not kill the target. Remote discovery retains its observations and reports a separate cleanup error if the temporary connection cannot be removed.
The [Frida Core API](https://frida.re/docs/frida-core-api/) documents device management, sessions, and script loading; the [JavaScript API](https://frida.re/docs/javascript-api/) documents target-side instrumentation. [Luma](https://luma.frida.re/) is Frida's standalone GUI; REA does not automate or control it. `npm run verify:frida` requires a Linux host with the optional Frida binding and uses a short-lived local Node.js fixture created by the verifier. Add `-- --address HOST:PORT --pid PID` to run the separate remote attach lane against a caller-selected target. Mock tests do not establish real device/server compatibility.
+1 -1
View File
@@ -49,7 +49,7 @@ For runtime instrumentation, see the [Frida guide](./frida-instrumentation.md).
| Task | Guides |
| --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Inspect native functions, references, or types | [Native binaries](native-investigation.md), [Go metadata](go-binaries.md), [offline ELF layout](binary-diagnostics.md), [recorded crashes](recorded-crashes.md) |
| Inspect native functions, references, or types | [Native binaries](native-investigation.md), [Go metadata](go-binaries.md), [Rust dependencies](rust-binaries.md), [offline ELF layout](binary-diagnostics.md), [recorded crashes](recorded-crashes.md) |
| Select a native provider or import format | [Ghidra semantics](ghidra-provider.md), [Windows](windows-ghidra-p0.md), [DOS](ghidra-dos.md), [raw bytes](raw-binary.md), [MIPS](ghidra-mips.md), [PSP](ghidra-psp.md), [NativeAOT](ghidra-nativeaot.md), [IDA](ida-provider.md), [JEB](jeb-analysis.md) |
| Analyze JavaScript or Electron artifacts | [Static analysis](javascript-artifact-reconstruction.md), [tracing and comparisons](javascript-application-workflows.md), [application graph](javascript-application-graph.md), [source recovery](javascript-recovery.md) |
| Compare static JavaScript with runtime observations | [Runtime attribution](javascript-runtime-observation.md), [reconciliation](javascript-runtime-reconciliation.md), [Electron observation](electron-observation.md) |
+3
View File
@@ -764,6 +764,9 @@ errors expose Error names, messages, and available codes under
truncation markers. Darwin ownership-helper compilation failures also retain
the compiler outcome, exit code or signal, and bounded stderr; a timed-out
compiler remains distinguishable from a compiler that exited with an error.
The helper compile deadline defaults to 120,000 ms; set
`REA_SWIFTC_COMPILE_TIMEOUT_MS` to an integer between 1 and 2,147,483,647 when
a busy host needs longer.
Other rejection values retain their primitive value or an explicit type.
Shutdown warnings include the failure
kind, message, and diagnostics, while process and temporary-project cleanup
+40 -9
View File
@@ -139,14 +139,40 @@ The result preserves the requested names in `selection.type_names` and reports
unmatched names separately. If metadata names are unreadable, limitations retain
that uncertainty. With no selection, `selection` is null and whole-assembly
inspection keeps its existing resource policy. Selection restricts types,
fields, methods, call edges and field accesses; member references remain an
assembly-wide inventory, so output size is not guaranteed to be small.
fields, methods, call edges, field accesses and user strings; member references
remain an assembly-wide inventory, so output size is not guaranteed to be small.
Coverage describes the selected members. Comparisons leave members outside the
opposite observation's selection unknown, and application graphs report their
selected scope as partial. Neither makes an absence claim about the whole
assembly. Older member Evidence without `selection` remains readable.
### User strings
`ldstr` anchors keep their build-local `0x70` tokens. `user_strings.literals`
lists each distinct token loaded by an inspected method body once, in token
order, with its `#US` file offset and decoded value. Values keep their stored
UTF-16 code units, including unpaired surrogates. Token `0x70000000` names the
heap's empty entry at offset 0 and reads as `""`; any other item there is
malformed. The terminal flag is checked against ECMA-335 II.24.2.4, and the
length prefix against the width II.23.2 assigns. A difference is reported with
its byte offset as a user-string issue while preserving the readable literal.
Toolchain conventions can differ; this conformance observation does not
establish runtime rejection. A missing `#US` stream is one stream-level issue;
a malformed item is reported against its token. User strings carry their own
coverage: any of these makes `user_strings.state` partial and lists the issue
in `user_strings.issues`, while the member `coverage` and `metadata.status` are
unaffected, and readable literals remain. The state is also partial when an
inspected method's CIL was not fully decoded (a malformed exception section
alone does not count) or a method that may belong to the inspected types was
not inspected (its row could not be read, or its type's name could not be read
under a `type_names` selection), because `ldstr` instructions there were not
observed. Normalized CIL digests do not include decoded values.
`compare_managed_members` does not decode or compare literals: an unchanged
method does not establish unchanged strings, and the comparison says so in its
limitations. Older member Evidence without `user_strings` reads as `null`: not
examined.
### Edge target declaring types
`member_refs[].parent_name`, `call_edges[].target_declaring_type`, and
@@ -183,9 +209,11 @@ native/runtime questions retain their own authority and coverage.
Names and semantic labels do not establish durable member identity. Comparison
preserves observed differences, structural inferences, and unknowns separately.
Cross-version matching first prefers exact CIL/signature identity. When that
does not match, it pairs an exact declared type, method name, and raw signature
before trying structural body shape. The exact-signature key uses names only
Cross-version matching first prefers exact raw CIL/signature identity, with
equal decoded fingerprints. Equal decoded fingerprints alone cannot establish
an exact match: they omit switch targets and collapse distinct NaN encodings.
When that does not match, it pairs an exact declared type, method name, and raw
signature before trying structural body shape. The exact-signature key uses names only
as part of that full tuple; names alone never select a pair. Duplicate tuples
remain ambiguous rather than being paired by token order. Fields follow the
same exact tiers. The raw signature is exact whether or not REA decoded it, so
@@ -196,8 +224,11 @@ unpaired member, one-sided or ambiguous, with the same declared type and name
whose signature was not decoded.
For a matched method, an unavailable or partial body makes body-shape facets
unknown while preserving observed signature differences. Structural identity
compares normalized signatures, the limited decoded-CIL tuple fingerprint,
unknown while preserving observed signature differences. For complete bodies,
a difference in either the raw CIL digest or the decoded fingerprint is reported
in the `cil` dimension, including reordered switch targets with equal decoded
fingerprints. Structural identity compares normalized signatures, the limited
decoded-CIL tuple fingerprint,
constants, and bounded shape context. It reports all candidates at the winning
score and remains ambiguous when the evidence does not distinguish them. The
digest does not itself remap metadata tokens.
@@ -334,8 +365,8 @@ Opcode names retain short/long forms and prefix opcodes. This makes the value a
reproducible decoded-tuple fingerprint, not a canonical semantic CIL identity:
it does not resolve tokens across MVIDs, does not commit full control flow or
exception semantics, and does not replace the raw CIL digest. Cross-build
comparison uses the value only as one unique-only structural tier and reports
ambiguity when that evidence is insufficient.
comparison requires equal raw CIL digests as well for exact CIL/signature
matches and reports ambiguity when structural evidence is insufficient.
For example, a decoded `nop; ret` body serializes exactly as
`[["nop","none",null],["ret","none",null]]` and has digest
+26
View File
@@ -21,6 +21,31 @@ directly to `compare_functions`, and `inspect_artifact` Evidence to
`compare_artifacts`. Use `get_evidence_bundle` when the task needs broader
retained session history or an explicit bundle for transfer.
Artifact inventories declare `coverage.scope` (`root` or `container-entries`)
and `coverage.status` (`complete` or `unknown`) independently of diagnostic
wording. Comparison requires matching scopes, complete graph members and complete
traversal coverage before concluding equality. A fully observed root without
container children can be `unchanged`; its scope notice stays in `limitations`
without creating a gap. Content and executable metadata changes still produce
root deltas. Missing graph members yield `truncated`; unknown traversal coverage
or unavailable occurrence hashes retain uncertainty. Integrity mismatches remain
contradictions. Static artifact equality does not establish unchanged runtime
behavior.
Exhausted traversals with deliberately omitted filesystem entries retain
`unknown` coverage and identify each omitted path/type in `limitations`; FIFO,
socket and device entries are not opened. Case-distinct archive members remain
separate observations. Their case-insensitive materialization diagnostic does
not reduce traversal coverage when both spellings were read.
Current output also retains `coverage_status` (`complete` or `partial`) for existing clients, derived from the scoped traversal status. The owning parser normalizes retained `coverage_status` records to scoped coverage and rejects conflicting declarations.
The coverage field is optional when reading older retained Evidence. The owning
inventory parser recognizes historical REA scope notices for compatibility;
unfamiliar legacy limitations remain conservative. Typed records do not derive
coverage from limitation text. Pages from one inventory must carry the same
coverage declaration.
Function dossiers can declare per-facet coverage in the optional
`normalized_result.facet_availability` map. Each supplied facet is either
`{ "available": true }` or `{ "available": false, "reason": "..." }`.
@@ -474,6 +499,7 @@ These deadlines have different owners:
| MCP initialize | The client bounds transport/REA connection startup, before any target query. |
| Hopper startup | REA allows 120,000 ms by default; `REA_HOPPER_STARTUP_TIMEOUT_MS` accepts decimal integers from 1–2,147,483,647 ms. Invalid values fail configuration validation. Startup failure is reported by the first provider query. |
| Ghidra startup | REA allows 330,000 ms by default; `REA_GHIDRA_STARTUP_TIMEOUT_MS` accepts decimal integers from 1–2,147,483,647 ms. Invalid supplied values fail configuration validation. Startup failure is reported by the first provider query. |
| Darwin swiftc helper | REA allows 120,000 ms by default for ownership-helper compilation; `REA_SWIFTC_COMPILE_TIMEOUT_MS` accepts decimal integers from 1–2,147,483,647 ms. Invalid values fail configuration validation. |
| Individual tool call | The client bounds its wait, including cold engine startup. The pinned client SDK 2.3.1 defaults to 60,000 ms and can cancel earlier than REA's startup deadline. |
For an already connected client using the pinned SDK, request options are the
+6 -1
View File
@@ -19,7 +19,11 @@
**[الموقع](https://rea.tools/ar/) · [الأدلة](https://rea.tools/ar/guides/) · [دراسات الحالة](https://rea.tools/ar/showcase/)**
[البدء السريع](#البدء-السريع) · [كيف يعمل REA](#كيف-يعمل-rea) · [ما الذي يمكنك تحليله](#ما-الذي-يمكنك-تحليله) · [دراسات الحالة](#دراسات-الحالة) · [الأسئلة الشائعة](#الأسئلة-الشائعة) · [التوثيق](#التوثيق)
[البدء السريع](#البدء-السريع) · [كيف يعمل REA](#كيف-يعمل-rea) · [ما الذي يمكنك تحليله](#ما-الذي-يمكنك-تحليله) · [دراسات الحالة](#دراسات-الحالة) · [الأسئلة الشائعة](#الأسئلة-الشائعة) · [أدوات GNU objdump وRizin](../reverse-engineering-tools.md) · [التوثيق](#التوثيق)
> [!IMPORTANT]
> المصادر الرسمية لـ REA: [morluto/rea](https://github.com/morluto/rea), [rea.tools](https://rea.tools/), [rea-agents](https://www.npmjs.com/package/rea-agents) (npm).
> استخدم روابط التثبيت والإصدارات المنشورة في هذه المصادر الرسمية. تشابه اسم المستودع أو نسخ ملف README لا يثبت أن التنزيل رسمي.
<code>npx rea-agents setup</code>
@@ -135,6 +139,7 @@ npx rea-agents@latest setup
| الملفات الثنائية للشيفرة الأصلية | شيفرة شبه برمجية، وتعليمات تجميع، وسلاسل نصية، ورموز، واستدعاءات، ومراجع | Hopper أو Ghidra أو IDA؛ [تحليل الشيفرة الأصلية](https://rea.tools/ar/guides/native/) |
| بنية ELF دون تشغيل | الأقسام والمقاطع والرموز ومعلومات إعادة التموضع الأصلية، وآليات الحماية المحتملة المستدلّ عليها بالفحص الثابت | pwntools يوفّره المستدعي على Linux x64؛ [تشخيص الملفات الثنائية](../binary-diagnostics.md) |
| شيفرة EVM البايتية | محددات التوجيه، وإزاحات البايتات، والمعاملات المستنتجة، وقابلية تغيير الحالة | مدخل محلي يحمل بايتات خامًا أو تمثيلًا سداسيًا عشريًا على Linux x64؛ [دليل EVM دون تشغيل](../evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| أعطال Linux المسجّلة | سجلات note الخام، ومسجّلات المعالج/الإشارات لكل خيط مسجّل، وترشيحات اختيارية لخرائط الذاكرة | pwntools يوفّره المستدعي على Linux x64؛ GDB/pwndbg اختياريان؛ [الأعطال المسجّلة](../recorded-crashes.md) |
| JavaScript / Electron | الوحدات، وعمليات الاستيراد، وخرائط المصدر، والمسارات، وIPC، وعلاقات إضافات الشيفرة الأصلية | Node.js وnpm؛ [تحليل التطبيقات](https://rea.tools/ar/guides/javascript/) |
| المواقع | بنية الصفحة، والسكربتات، وملاحظات الشبكة، ولقطات الشاشة المطلوبة | متصفح من عائلة Chrome؛ [تحليل المتصفح](https://rea.tools/ar/guides/browser/) |
+6 -1
View File
@@ -19,7 +19,11 @@
**[Website](https://rea.tools/de/) · [Anleitungen](https://rea.tools/de/guides/) · [Fallstudien](https://rea.tools/de/showcase/)**
[Schnellstart](#schnellstart) · [So funktioniert REA](#so-funktioniert-rea) · [Was du analysieren kannst](#was-du-analysieren-kannst) · [Fallstudien](#fallstudien) · [Häufige Fragen](#häufige-fragen) · [Dokumentation](#dokumentation)
[Schnellstart](#schnellstart) · [So funktioniert REA](#so-funktioniert-rea) · [Was du analysieren kannst](#was-du-analysieren-kannst) · [Fallstudien](#fallstudien) · [Häufige Fragen](#häufige-fragen) · [GNU-objdump- und Rizin-Tools](../reverse-engineering-tools.md) · [Dokumentation](#dokumentation)
> [!IMPORTANT]
> Offizielle Quellen für REA: [morluto/rea](https://github.com/morluto/rea), [rea.tools](https://rea.tools/), [rea-agents](https://www.npmjs.com/package/rea-agents) (npm).
> Folge den Installations- und Release-Links aus diesen offiziellen Quellen. Ein ähnlicher Repository-Name oder eine kopierte README belegt nicht, dass ein Download offiziell ist.
<code>npx rea-agents setup</code>
@@ -135,6 +139,7 @@ REA benötigt Node.js 22.x (>=22.19), 24.x (>=24.11) oder 26+ sowie npm. Zusätz
| Native Binärdateien | Pseudocode, Assemblercode, Zeichenketten, Symbole, Aufrufe und Verweise | Hopper, Ghidra oder IDA; [native Analyse](https://rea.tools/de/guides/native/) |
| Offline-ELF-Struktur | Sektionen, Segmente, ursprüngliche Symbole/Relokationen und mögliche Schutzmaßnahmen aus statischer Analyse | Vom Aufrufer bereitgestelltes pwntools unter Linux x64; [Binärdiagnostik](../binary-diagnostics.md) |
| EVM-Bytecode | Dispatch-Selektoren, Byte-Offsets, abgeleitete Argumente und Veränderbarkeit des Zustands | Lokale Eingabe mit Rohbytes oder Hexdarstellung unter Linux x64; [Offline-EVM-Leitfaden](../evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| Aufgezeichnete Linux-Abstürze | Unverarbeitete Note-Einträge, Register/Signale aller aufgezeichneten Threads und optionale Zuordnungskandidaten | Vom Aufrufer bereitgestelltes pwntools unter Linux x64; optional GDB/pwndbg; [aufgezeichnete Abstürze](../recorded-crashes.md) |
| JavaScript / Electron | Module, Imports, Source Maps, Routen, IPC und Beziehungen zu nativen Add-ons | Node.js und npm; [Anwendungsanalyse](https://rea.tools/de/guides/javascript/) |
| Websites | Seitenstruktur, Skripte, Netzwerkbeobachtungen und angeforderte Screenshots | Ein Browser aus der Chrome-Familie; [Browseranalyse](https://rea.tools/de/guides/browser/) |
+6 -1
View File
@@ -19,7 +19,11 @@
**[Sitio web](https://rea.tools/es/) · [Guías](https://rea.tools/es/guides/) · [Casos prácticos](https://rea.tools/es/showcase/)**
[Inicio rápido](#inicio-rápido) · [Cómo funciona REA](#cómo-funciona-rea) · [Qué puedes analizar](#qué-puedes-analizar) · [Casos prácticos](#casos-prácticos) · [Preguntas frecuentes](#preguntas-frecuentes) · [Documentación](#documentación)
[Inicio rápido](#inicio-rápido) · [Cómo funciona REA](#cómo-funciona-rea) · [Qué puedes analizar](#qué-puedes-analizar) · [Casos prácticos](#casos-prácticos) · [Preguntas frecuentes](#preguntas-frecuentes) · [Herramientas GNU objdump y Rizin](../reverse-engineering-tools.md) · [Documentación](#documentación)
> [!IMPORTANT]
> Fuentes oficiales de REA: [morluto/rea](https://github.com/morluto/rea), [rea.tools](https://rea.tools/), [rea-agents](https://www.npmjs.com/package/rea-agents) (npm).
> Usa los enlaces de instalación y de versiones publicados en estas fuentes oficiales. Un nombre de repositorio parecido o un README copiado no demuestra que una descarga sea oficial.
<code>npx rea-agents setup</code>
@@ -135,6 +139,7 @@ REA requiere Node.js 22.x (>=22.19), 24.x (>=24.11) o 26+, además de npm. Las h
| Binarios nativos | Pseudocódigo, ensamblador, cadenas, símbolos, llamadas y referencias | Hopper, Ghidra o IDA; [análisis nativo](https://rea.tools/es/guides/native/) |
| Estructura ELF sin ejecutar | Secciones, segmentos, símbolos/reubicaciones originales y posibles medidas de mitigación detectadas mediante análisis estático | pwntools proporcionado por quien llama, en Linux x64; [diagnóstico de binarios](../binary-diagnostics.md) |
| Bytecode EVM | Selectores de despacho, desplazamientos en bytes, argumentos inferidos y mutabilidad | Entrada local con bytes sin procesar o representación hexadecimal, en Linux x64; [guía de EVM sin ejecutar](../evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| Fallos de Linux registrados | Registros note sin procesar, registros/señales de cada hilo registrado y posibles correspondencias de memoria opcionales | pwntools proporcionado por quien llama, en Linux x64; GDB/pwndbg opcionales; [fallos registrados](../recorded-crashes.md) |
| JavaScript / Electron | Módulos, importaciones, mapas de código fuente, rutas, IPC y relaciones con complementos nativos | Node.js y npm; [análisis de aplicaciones](https://rea.tools/es/guides/javascript/) |
| Sitios web | Estructura de la página, scripts, observaciones de red y capturas de pantalla solicitadas | Un navegador de la familia Chrome; [análisis del navegador](https://rea.tools/es/guides/browser/) |
+6 -1
View File
@@ -19,7 +19,11 @@
**[وب‌سایت](https://rea.tools/fa/) · [راهنماها](https://rea.tools/fa/guides/) · [نمونه‌های عملی](https://rea.tools/fa/showcase/)**
[شروع سریع](#شروع-سریع) · [REA چگونه کار می‌کند؟](#rea-چگونه-کار-می‌کند) · [چه چیزهایی را میتوان تحلیل کرد؟](#چه-چیزهایی-را-می‌توان-تحلیل-کرد) · [نمونه‌های عملی](#نمونه‌های-عملی) · [پرسش‌های متداول](#پرسش‌های-متداول) · [مستندات](#مستندات)
[شروع سریع](#شروع-سریع) · [REA چگونه کار می‌کند؟](#rea-چگونه-کار-می‌کند) · [چه چیزهایی را میتوان تحلیل کرد؟](#چه-چیزهایی-را-می‌توان-تحلیل-کرد) · [نمونه‌های عملی](#نمونه‌های-عملی) · [پرسش‌های متداول](#پرسش‌های-متداول) · [ابزارهای GNU objdump و Rizin](../reverse-engineering-tools.md) · [مستندات](#مستندات)
> [!IMPORTANT]
> منابع رسمی REA: [morluto/rea](https://github.com/morluto/rea), [rea.tools](https://rea.tools/), [rea-agents](https://www.npmjs.com/package/rea-agents) (npm).
> از پیوندهای نصب و انتشار در این منابع رسمی استفاده کنید. نام مشابه مخزن یا README کپی‌شده ثابت نمی‌کند که فایل دانلودی رسمی است.
<code>npx rea-agents setup</code>
@@ -127,6 +131,7 @@ REA به Node.js 22.x (>=22.19)، 24.x (>=24.11) یا 26+، به‌همراه np
| باینری‌های بومی | شبه‌کد، اسمبلی، رشته‌ها، نمادها، فراخوانی‌ها و ارجاعات | Hopper، Ghidra یا IDA؛ [تحلیل بومی](https://rea.tools/fa/guides/native/) |
| ساختار ELF آفلاین | بخش‌ها، سگمنت‌ها، نمادها و relocationهای اصلی و گزینه‌های احتمالی کاهش آسیب‌پذیری ایستا | pwntools تأمین‌شده توسط فراخواننده روی Linux x64؛ [تشخیص باینری](../binary-diagnostics.md) |
| بایت‌کد EVM | selectorهای dispatch، offsetهای بایتی، آرگومان‌های استنباط‌شده و قابلیت تغییر وضعیت | دادهٔ خام/hex محلی روی Linux x64؛ [راهنمای EVM آفلاین](../evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| کرش‌های ثبت‌شدهٔ لینوکس | یادداشت‌های خام، رجیسترها/سیگنال‌های تمام threadهای ثبت‌شده و گزینه‌های احتمالی نگاشت | pwntools تأمین‌شده توسط فراخواننده روی Linux x64؛ GDB/pwndbg اختیاری؛ [کرش‌های ثبت‌شده](../recorded-crashes.md) |
| JavaScript / Electron | ماژول‌ها، importها، source mapها، مسیرها، IPC و ارتباط افزونه‌های بومی | Node.js و npm؛ [تحلیل برنامه](https://rea.tools/fa/guides/javascript/) |
| وب‌سایت‌ها | ساختار صفحه، اسکریپت‌ها، مشاهدات شبکه و اسکرین‌شات‌های درخواستی | مرورگر مبتنی بر Chrome؛ [تحلیل مرورگر](https://rea.tools/fa/guides/browser/) |
+6 -1
View File
@@ -19,7 +19,11 @@
**[Site web](https://rea.tools/fr/) · [Guides](https://rea.tools/fr/guides/) · [Études de cas](https://rea.tools/fr/showcase/)**
[Démarrage rapide](#démarrage-rapide) · [Comment fonctionne REA](#comment-fonctionne-rea) · [Ce que vous pouvez analyser](#ce-que-vous-pouvez-analyser) · [Études de cas](#études-de-cas) · [Questions fréquentes](#questions-fréquentes) · [Documentation](#documentation)
[Démarrage rapide](#démarrage-rapide) · [Comment fonctionne REA](#comment-fonctionne-rea) · [Ce que vous pouvez analyser](#ce-que-vous-pouvez-analyser) · [Études de cas](#études-de-cas) · [Questions fréquentes](#questions-fréquentes) · [Outils GNU objdump et Rizin](../reverse-engineering-tools.md) · [Documentation](#documentation)
> [!IMPORTANT]
> Sources officielles de REA : [morluto/rea](https://github.com/morluto/rea), [rea.tools](https://rea.tools/), [rea-agents](https://www.npmjs.com/package/rea-agents) (npm).
> Utilisez les liens d’installation et de publication de ces sources officielles. Un nom de dépôt similaire ou un README copié ne prouve pas qu’un téléchargement est officiel.
<code>npx rea-agents setup</code>
@@ -139,6 +143,7 @@ REA nécessite Node.js 22.x (>=22.19), 24.x (>=24.11) ou 26+, ainsi que npm. Les
| Structure ELF hors ligne | Sections, segments, symboles et relocations d'origine, et protections statiques candidates | pwntools fourni par l'utilisateur sous Linux x64 ; [diagnostics binaires](../binary-diagnostics.md) |
| Artefact WASM | Validation, sections, formes WAT exactes d'import/export et WAT décodé | WABT 1.0.42 fourni par l'utilisateur ; `inspect_wasm_artifact` |
| Bytecode EVM | Sélecteurs de dispatch, offsets en octets, arguments inférés et mutabilité | Fichier local brut ou hexadécimal sous Linux x64 ; [guide EVM hors ligne](../evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| Crashs Linux enregistrés | Notes brutes, registres et signaux de chaque thread enregistré, et correspondances de mappings facultatives | pwntools fourni par l'utilisateur sous Linux x64 ; GDB/pwndbg en option ; [crashs enregistrés](../recorded-crashes.md) |
| JavaScript / Electron | Modules, imports, source maps, routes, IPC et relations avec les modules natifs | Node.js et npm ; [analyse d'applications](https://rea.tools/fr/guides/javascript/) |
| Sites web | Structure des pages, scripts, observations réseau et captures d'écran demandées | Un navigateur de la famille Chrome ; [analyse du navigateur](https://rea.tools/fr/guides/browser/) |
+6 -1
View File
@@ -19,7 +19,11 @@
**[Situs Web](https://rea.tools/id/) · [Panduan](https://rea.tools/id/guides/) · [Contoh Penggunaan](https://rea.tools/id/showcase/)**
[Mulai Cepat](#mulai-cepat) · [Cara Kerja REA](#cara-kerja-rea) · [Hal yang Dapat Anda Analisis](#hal-yang-dapat-anda-analisis) · [Contoh Penggunaan](#contoh-penggunaan) · [FAQ](#faq) · [Dokumentasi](#dokumentasi)
[Mulai Cepat](#mulai-cepat) · [Cara Kerja REA](#cara-kerja-rea) · [Hal yang Dapat Anda Analisis](#hal-yang-dapat-anda-analisis) · [Contoh Penggunaan](#contoh-penggunaan) · [FAQ](#faq) · [Alat GNU objdump dan Rizin](../reverse-engineering-tools.md) · [Dokumentasi](#dokumentasi)
> [!IMPORTANT]
> Sumber resmi REA: [morluto/rea](https://github.com/morluto/rea), [rea.tools](https://rea.tools/), [rea-agents](https://www.npmjs.com/package/rea-agents) (npm).
> Gunakan tautan instalasi dan rilis dari sumber resmi ini. Nama repositori yang mirip atau README yang disalin tidak membuktikan bahwa unduhan tersebut resmi.
<code>npx rea-agents setup</code>
@@ -142,6 +146,7 @@ Alat tambahan dan dukungan sistem host bergantung pada target yang dianalisis:
| Tata letak ELF offline | Bagian, segmen, simbol/relokasi asli, dan kandidat mitigasi statis | pwntools yang disediakan pemanggil pada Linux x64; [diagnostik biner](../binary-diagnostics.md) |
| Artefak WASM | Validasi, bagian, bentuk WAT import/ekspor yang tepat, dan WAT yang didekode | WABT 1.0.42 yang disediakan pemanggil; `inspect_wasm_artifact` |
| Bytecode EVM | Selector dispatch, offset byte, argumen yang disimpulkan, dan sifat mutabilitas | Pembawa data raw/hex lokal; [panduan EVM offline](../evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| Crash Linux yang direkam | Catatan mentah, register/sinyal setiap thread yang direkam, dan kandidat pemetaan opsional | pwntools yang disediakan pemanggil; GDB/pwndbg opsional; [crash yang direkam](../recorded-crashes.md) |
| JavaScript / Electron | Modul, impor, source map, rute, IPC, dan hubungan add-on native | Node.js dan npm; [analisis aplikasi](https://rea.tools/id/guides/javascript/) |
| Situs web | Struktur halaman, skrip, pengamatan jaringan, dan tangkapan layar yang diminta | Peramban berbasis Chrome; [analisis peramban](https://rea.tools/id/guides/browser/) |
+6 -1
View File
@@ -19,7 +19,11 @@
**[Sito web](https://rea.tools/it/) · [Guide](https://rea.tools/it/guides/) · [Showcase](https://rea.tools/it/showcase/)**
[Avvio rapido](#avvio-rapido) · [Come funziona REA](#come-funziona-rea) · [Cosa puoi analizzare](#cosa-puoi-analizzare) · [Showcase](#showcase) · [FAQ](#faq) · [Documentazione](#documentazione)
[Avvio rapido](#avvio-rapido) · [Come funziona REA](#come-funziona-rea) · [Cosa puoi analizzare](#cosa-puoi-analizzare) · [Showcase](#showcase) · [FAQ](#faq) · [Strumenti GNU objdump e Rizin](../reverse-engineering-tools.md) · [Documentazione](#documentazione)
> [!IMPORTANT]
> Fonti ufficiali di REA: [morluto/rea](https://github.com/morluto/rea), [rea.tools](https://rea.tools/), [rea-agents](https://www.npmjs.com/package/rea-agents) (npm).
> Segui i link di installazione e delle versioni pubblicate da queste fonti ufficiali. Un nome di repository simile o un README copiato non dimostra che un download sia ufficiale.
<code>npx rea-agents setup</code>
@@ -139,6 +143,7 @@ REA richiede Node.js 22.x (>=22.19), 24.x (>=24.11) o 26+, oltre a npm. Strument
| Layout ELF offline | Sezioni, segmenti, simboli/relocazioni originali e candidati mitigazioni statiche | pwntools fornito dal chiamante su Linux x64; [diagnostica binaria](../binary-diagnostics.md) |
| Artefatto WASM | Convalida, sezioni, forme WAT di import/export esatte e WAT decodificato | WABT 1.0.42 fornito dal chiamante; `inspect_wasm_artifact` |
| Bytecode EVM | Selettori di dispatch, offset dei byte, argomenti inferiti e mutabilità | Carrier raw/hex locale; [guida EVM offline](../evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| Crash Linux registrati | Note grezze, registri/segnai di ogni thread registrato e candidati mapping opzionali | pwntools fornito dal chiamante; GDB/pwndbg opzionale; [crash registrati](../recorded-crashes.md) |
| JavaScript / Electron | Moduli, import, source map, route, IPC e relazioni con add-on nativi | Node.js e npm; [analisi delle applicazioni](https://rea.tools/it/guides/javascript/) |
| Siti web | Struttura della pagina, script, osservazioni di rete e screenshot richiesti | Un browser della famiglia Chrome; [analisi browser](https://rea.tools/it/guides/browser/) |
+6 -1
View File
@@ -19,7 +19,11 @@
**[ウェブサイト](https://rea.tools/ja/) · [ガイド](https://rea.tools/ja/guides/) · [事例](https://rea.tools/ja/showcase/)**
[クイックスタート](#クイックスタート) · [REA の仕組み](#rea-の仕組み) · [分析できる対象](#分析できる対象) · [事例](#事例) · [よくある質問](#よくある質問) · [ドキュメント](#ドキュメント)
[クイックスタート](#クイックスタート) · [REA の仕組み](#rea-の仕組み) · [分析できる対象](#分析できる対象) · [事例](#事例) · [よくある質問](#よくある質問) · [GNU objdump・Rizin ツール](../reverse-engineering-tools.md) · [ドキュメント](#ドキュメント)
> [!IMPORTANT]
> REA の公式配布元: [morluto/rea](https://github.com/morluto/rea), [rea.tools](https://rea.tools/), [rea-agents](https://www.npmjs.com/package/rea-agents) (npm).
> インストールとリリースのリンクは、これらの公式配布元からたどってください。似たリポジトリ名やコピーされた README だけでは、公式の配布物とは確認できません。
<code>npx rea-agents setup</code>
@@ -135,6 +139,7 @@ REA には Node.js 22.x(>=22.19)、24.x(>=24.11)、または 26+ と npm
| ネイティブバイナリ | 疑似コード、アセンブリ、文字列、シンボル、呼び出し、参照 | Hopper、Ghidra、または IDA;[ネイティブ分析](https://rea.tools/ja/guides/native/) |
| オフライン ELF レイアウト | セクション、セグメント、元のシンボル/再配置情報、静的解析によるセキュリティ対策の候補 | Linux x64 で利用者が用意する pwntools;[バイナリ診断](../binary-diagnostics.md) |
| EVM バイトコード | ディスパッチセレクター、バイトオフセット、推定された引数と状態変更の可否 | Linux x64 上のローカルの生バイト/16 進数の入力ファイル;[オフライン EVM ガイド](../evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| 記録済みの Linux クラッシュ | 生の note レコード、記録された全スレッドのレジスター/シグナル、任意のマッピング候補 | Linux x64 で利用者が用意する pwntools;GDB/pwndbg は任意;[記録済みクラッシュ](../recorded-crashes.md) |
| JavaScript / Electron | モジュール、インポート、ソースマップ、ルート、IPC、ネイティブアドオンの関係 | Node.js と npm;[アプリケーション分析](https://rea.tools/ja/guides/javascript/) |
| ウェブサイト | ページ構造、スクリプト、ネットワークの観測結果、依頼されたスクリーンショット | Chrome 系ブラウザー;[ブラウザー分析](https://rea.tools/ja/guides/browser/) |
+6 -1
View File
@@ -19,7 +19,11 @@
**[웹사이트](https://rea.tools/ko/) · [가이드](https://rea.tools/ko/guides/) · [사례](https://rea.tools/ko/showcase/)**
[빠른 시작](#빠른-시작) · [REA의 작동 방식](#rea의-작동-방식) · [분석할 수 있는 대상](#분석할-수-있는-대상) · [사례](#사례) · [자주 묻는 질문](#자주-묻는-질문) · [문서](#문서)
[빠른 시작](#빠른-시작) · [REA의 작동 방식](#rea의-작동-방식) · [분석할 수 있는 대상](#분석할-수-있는-대상) · [사례](#사례) · [자주 묻는 질문](#자주-묻는-질문) · [GNU objdump 및 Rizin 도구](../reverse-engineering-tools.md) · [문서](#문서)
> [!IMPORTANT]
> REA 공식 배포처: [morluto/rea](https://github.com/morluto/rea), [rea.tools](https://rea.tools/), [rea-agents](https://www.npmjs.com/package/rea-agents) (npm).
> 이 공식 배포처에서 제공하는 설치 및 릴리스 링크를 이용하세요. 비슷한 저장소 이름이나 복사된 README만으로는 공식 배포 파일인지 확인할 수 없습니다.
<code>npx rea-agents setup</code>
@@ -135,6 +139,7 @@ REA에는 Node.js 22.x(>=22.19), 24.x(>=24.11) 또는 26+와 npm이 필요합니
| 네이티브 바이너리 | 의사 코드, 어셈블리, 문자열, 심볼, 호출, 참조 | Hopper, Ghidra 또는 IDA; [네이티브 분석](https://rea.tools/ko/guides/native/) |
| 오프라인 ELF 레이아웃 | 섹션, 세그먼트, 원본 심볼/재배치 정보, 정적 분석으로 얻은 보안 완화 기법 후보 | Linux x64에서 호출자가 제공하는 pwntools; [바이너리 진단](../binary-diagnostics.md) |
| EVM 바이트코드 | 디스패치 선택자, 바이트 오프셋, 추론한 인자와 상태 변경 가능 여부 | Linux x64의 로컬 원시 바이트/16진수 입력 파일; [오프라인 EVM 가이드](../evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| 기록된 Linux 크래시 | 원시 note 레코드, 기록된 모든 스레드의 레지스터/시그널, 선택적 매핑 후보 | Linux x64에서 호출자가 제공하는 pwntools; GDB/pwndbg는 선택 사항; [기록된 크래시](../recorded-crashes.md) |
| JavaScript / Electron | 모듈, 임포트, 소스 맵, 라우트, IPC, 네이티브 애드온 관계 | Node.js와 npm; [애플리케이션 분석](https://rea.tools/ko/guides/javascript/) |
| 웹사이트 | 페이지 구조, 스크립트, 네트워크 관찰 결과, 요청한 스크린샷 | Chrome 계열 브라우저; [브라우저 분석](https://rea.tools/ko/guides/browser/) |
+6 -1
View File
@@ -19,7 +19,11 @@
**[Strona internetowa](https://rea.tools/pl/) · [Przewodniki](https://rea.tools/pl/guides/) · [Przykłady zastosowań](https://rea.tools/pl/showcase/)**
[Szybki start](#szybki-start) · [Jak działa REA](#jak-działa-rea) · [Co możesz analizować](#co-możesz-analizować) · [Przykłady zastosowań](#przykłady-zastosowań) · [FAQ](#faq) · [Dokumentacja](#dokumentacja)
[Szybki start](#szybki-start) · [Jak działa REA](#jak-działa-rea) · [Co możesz analizować](#co-możesz-analizować) · [Przykłady zastosowań](#przykłady-zastosowań) · [FAQ](#faq) · [Narzędzia GNU objdump i Rizin](../reverse-engineering-tools.md) · [Dokumentacja](#dokumentacja)
> [!IMPORTANT]
> Oficjalne źródła REA: [morluto/rea](https://github.com/morluto/rea), [rea.tools](https://rea.tools/), [rea-agents](https://www.npmjs.com/package/rea-agents) (npm).
> Korzystaj z odnośników do instalacji i wydań w tych oficjalnych źródłach. Podobna nazwa repozytorium lub skopiowany README nie potwierdzają, że pobierany plik jest oficjalny.
<code>npx rea-agents setup</code>
@@ -135,6 +139,7 @@ REA wymaga Node.js 22.x (>=22.19), 24.x (>=24.11) lub 26+ oraz npm. Dodatkowe na
| Natywne pliki binarne | Pseudokod, kod asemblera, ciągi znaków, symbole, wywołania i odwołania | Hopper, Ghidra lub IDA; [analiza kodu natywnego](https://rea.tools/pl/guides/native/) |
| Układ pliku ELF w trybie offline | Sekcje, segmenty, oryginalne symbole/relokacje i potencjalne mechanizmy zabezpieczeń wskazane przez analizę statyczną | pwntools dostarczone przez użytkownika w systemie Linux x64; [diagnostyka plików binarnych](../binary-diagnostics.md) |
| Kod bajtowy EVM | Selektory wywołań, przesunięcia bajtowe, wywnioskowane argumenty i mutowalność | Lokalny plik z surowymi bajtami lub zapisem szesnastkowym w systemie Linux x64; [przewodnik EVM offline](../evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| Zarejestrowane awarie systemu Linux | Surowe rekordy note, rejestry/sygnały każdego zarejestrowanego wątku i opcjonalni kandydaci na mapowania | pwntools dostarczone przez użytkownika w systemie Linux x64; opcjonalnie GDB/pwndbg; [zarejestrowane awarie](../recorded-crashes.md) |
| JavaScript / Electron | Moduły, importy, mapy źródeł, trasy, IPC i powiązania z natywnymi dodatkami | Node.js i npm; [analiza aplikacji](https://rea.tools/pl/guides/javascript/) |
| Strony internetowe | Struktura strony, skrypty, obserwacje sieciowe i zamówione zrzuty ekranu | Przeglądarka z rodziny Chrome; [analiza w przeglądarce](https://rea.tools/pl/guides/browser/) |
+6 -1
View File
@@ -19,7 +19,11 @@
**[Site](https://rea.tools/pt-BR/) · [Guias](https://rea.tools/pt-BR/guides/) · [Casos de uso](https://rea.tools/pt-BR/showcase/)**
[Início rápido](#início-rápido) · [Como o REA funciona](#como-o-rea-funciona) · [O que você pode analisar](#o-que-você-pode-analisar) · [Casos de uso](#casos-de-uso) · [Perguntas frequentes](#perguntas-frequentes) · [Documentação](#documentação)
[Início rápido](#início-rápido) · [Como o REA funciona](#como-o-rea-funciona) · [O que você pode analisar](#o-que-você-pode-analisar) · [Casos de uso](#casos-de-uso) · [Perguntas frequentes](#perguntas-frequentes) · [Ferramentas GNU objdump e Rizin](../reverse-engineering-tools.md) · [Documentação](#documentação)
> [!IMPORTANT]
> Fontes oficiais do REA: [morluto/rea](https://github.com/morluto/rea), [rea.tools](https://rea.tools/), [rea-agents](https://www.npmjs.com/package/rea-agents) (npm).
> Use os links de instalação e de versões dessas fontes oficiais. Um nome de repositório parecido ou um README copiado não comprova que um download seja oficial.
<code>npx rea-agents setup</code>
@@ -135,6 +139,7 @@ O REA requer Node.js 22.x (>=22.19), 24.x (>=24.11) ou 26+, além do npm. As fer
| Binários nativos | Pseudocódigo, assembly, strings, símbolos, chamadas e referências | Hopper, Ghidra ou IDA; [análise nativa](https://rea.tools/pt-BR/guides/native/) |
| Estrutura ELF sem execução | Seções, segmentos, símbolos/relocações originais e possíveis mecanismos de mitigação identificados por análise estática | pwntools fornecido pelo chamador no Linux x64; [diagnóstico de binários](../binary-diagnostics.md) |
| Bytecode EVM | Seletores de despacho, offsets de bytes, argumentos inferidos e mutabilidade | Entrada local com bytes brutos ou representação hexadecimal no Linux x64; [guia de EVM sem execução](../evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| Falhas do Linux registradas | Registros note brutos, registradores/sinais de cada thread registrada e candidatos opcionais a mapeamentos | pwntools fornecido pelo chamador no Linux x64; GDB/pwndbg opcionais; [falhas registradas](../recorded-crashes.md) |
| JavaScript / Electron | Módulos, importações, source maps, rotas, IPC e relações com complementos nativos | Node.js e npm; [análise de aplicativos](https://rea.tools/pt-BR/guides/javascript/) |
| Sites | Estrutura da página, scripts, observações de rede e capturas de tela solicitadas | Um navegador da família Chrome; [análise do navegador](https://rea.tools/pt-BR/guides/browser/) |
+6 -1
View File
@@ -19,7 +19,11 @@
**[Сайт](https://rea.tools/ru/) · [Руководства](https://rea.tools/ru/guides/) · [Примеры](https://rea.tools/ru/showcase/)**
[Быстрый старт](#быстрый-старт) · [Как работает REA](#как-работает-rea) · [Что можно анализировать](#что-можно-анализировать) · [Примеры](#примеры) · [Частые вопросы](#частые-вопросы) · [Документация](#документация)
[Быстрый старт](#быстрый-старт) · [Как работает REA](#как-работает-rea) · [Что можно анализировать](#что-можно-анализировать) · [Примеры](#примеры) · [Частые вопросы](#частые-вопросы) · [Инструменты GNU objdump и Rizin](../reverse-engineering-tools.md) · [Документация](#документация)
> [!IMPORTANT]
> Официальные источники REA: [morluto/rea](https://github.com/morluto/rea), [rea.tools](https://rea.tools/), [rea-agents](https://www.npmjs.com/package/rea-agents) (npm).
> Используйте ссылки на установку и выпуски из этих официальных источников. Похожее название репозитория или скопированный README не подтверждают, что скачиваемый файл является официальным.
<code>npx rea-agents setup</code>
@@ -135,6 +139,7 @@ REA требует Node.js 22.x (>=22.19), 24.x (>=24.11) или 26+, а так
| Нативные бинарные файлы | Псевдокод, ассемблер, строки, символы, вызовы и ссылки | Hopper, Ghidra или IDA; [нативный анализ](https://rea.tools/ru/guides/native/) |
| Структура ELF без запуска | Секции, сегменты, исходные символы/релокации и возможные механизмы защиты по данным статического анализа | pwntools, предоставленный вызывающей стороной, в Linux x64; [диагностика бинарных файлов](../binary-diagnostics.md) |
| Байт-код EVM | Селекторы диспетчеризации, смещения байтов, предполагаемые аргументы и изменяемость состояния | Локальные необработанные байты или шестнадцатеричное представление в Linux x64; [руководство по EVM без запуска](../evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| Записанные сбои Linux | Необработанные записи note, регистры/сигналы каждого записанного потока и необязательные кандидаты сопоставления с памятью | pwntools, предоставленный вызывающей стороной, в Linux x64; необязательные GDB/pwndbg; [записанные сбои](../recorded-crashes.md) |
| JavaScript / Electron | Модули, импорты, карты исходного кода, маршруты, IPC и связи с нативными дополнениями | Node.js и npm; [анализ приложений](https://rea.tools/ru/guides/javascript/) |
| Сайты | Структура страницы, скрипты, наблюдения за сетью и запрошенные снимки экрана | Браузер семейства Chrome; [анализ браузера](https://rea.tools/ru/guides/browser/) |
+6 -1
View File
@@ -19,7 +19,11 @@
**[เว็บไซต์](https://rea.tools/th/) · [คู่มือ](https://rea.tools/th/guides/) · [ตัวอย่างการใช้งาน](https://rea.tools/th/showcase/)**
[เริ่มต้นอย่างรวดเร็ว](#เริ่มต้นอย่างรวดเร็ว) · [REA ทำงานอย่างไร](#rea-ทำงานอย่างไร) · [สิ่งที่วิเคราะห์ได้](#สิ่งที่วิเคราะห์ได้) · [ตัวอย่างการใช้งาน](#ตัวอย่างการใช้งาน) · [คำถามที่พบบ่อย](#คำถามที่พบบ่อย) · [เอกสาร](#เอกสาร)
[เริ่มต้นอย่างรวดเร็ว](#เริ่มต้นอย่างรวดเร็ว) · [REA ทำงานอย่างไร](#rea-ทำงานอย่างไร) · [สิ่งที่วิเคราะห์ได้](#สิ่งที่วิเคราะห์ได้) · [ตัวอย่างการใช้งาน](#ตัวอย่างการใช้งาน) · [คำถามที่พบบ่อย](#คำถามที่พบบ่อย) · [เครื่องมือ GNU objdump และ Rizin](../reverse-engineering-tools.md) · [เอกสาร](#เอกสาร)
> [!IMPORTANT]
> แหล่งทางการของ REA: [morluto/rea](https://github.com/morluto/rea), [rea.tools](https://rea.tools/), [rea-agents](https://www.npmjs.com/package/rea-agents) (npm).
> โปรดใช้ลิงก์ติดตั้งและรุ่นเผยแพร่จากแหล่งทางการเหล่านี้ ชื่อที่เก็บโค้ดที่คล้ายกันหรือ README ที่คัดลอกมาไม่ได้ยืนยันว่าไฟล์ดาวน์โหลดเป็นของทางการ
<code>npx rea-agents setup</code>
@@ -135,6 +139,7 @@ REA ต้องใช้ Node.js 22.x (>=22.19), 24.x (>=24.11) หรือ 26
| ไบนารีเนทีฟ | โค้ดเทียม แอสเซมบลี สตริง สัญลักษณ์ การเรียก และการอ้างอิง | Hopper, Ghidra หรือ IDA; [การวิเคราะห์เนทีฟ](https://rea.tools/th/guides/native/) |
| โครงสร้าง ELF แบบออฟไลน์ | เซกชัน เซกเมนต์ สัญลักษณ์/รีโลเคชันต้นฉบับ และตัวเลือกกลไกป้องกันที่พบจากการวิเคราะห์แบบสถิต | pwntools ที่ผู้ใช้จัดเตรียมบน Linux x64; [การวินิจฉัยไบนารี](../binary-diagnostics.md) |
| ไบต์โค้ด EVM | ตัวเลือกฟังก์ชันสำหรับการเรียก ออฟเซ็ตไบต์ อาร์กิวเมนต์และความสามารถในการเปลี่ยนสถานะที่อนุมานได้ | ไฟล์บนเครื่องที่มีไบต์ดิบหรือข้อมูลเลขฐานสิบหกบน Linux x64; [คู่มือ EVM แบบออฟไลน์](../evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| ข้อมูลการแครชของ Linux ที่บันทึกไว้ | ระเบียน note ดิบ รีจิสเตอร์/สัญญาณของทุกเธรดที่บันทึกไว้ และตัวเลือกการแมปเพิ่มเติม | pwntools ที่ผู้ใช้จัดเตรียมบน Linux x64; เลือกใช้ GDB/pwndbg เพิ่มเติมได้; [การแครชที่บันทึกไว้](../recorded-crashes.md) |
| JavaScript / Electron | โมดูล การนำเข้า ซอร์สแมป เส้นทาง IPC และความสัมพันธ์กับส่วนเสริมเนทีฟ | Node.js และ npm; [การวิเคราะห์แอปพลิเคชัน](https://rea.tools/th/guides/javascript/) |
| เว็บไซต์ | โครงสร้างหน้า สคริปต์ ข้อมูลเครือข่ายที่สังเกตได้ และภาพหน้าจอที่ร้องขอ | เบราว์เซอร์ในตระกูล Chrome; [การวิเคราะห์ผ่านเบราว์เซอร์](https://rea.tools/th/guides/browser/) |
+6 -1
View File
@@ -19,7 +19,11 @@
**[Web sitesi](https://rea.tools/tr/) · [Rehberler](https://rea.tools/tr/guides/) · [Örnek çalışmalar](https://rea.tools/tr/showcase/)**
[Hızlı başlangıç](#hızlı-başlangıç) · [REA nasıl çalışır](#rea-nasıl-çalışır) · [Neleri analiz edebilirsiniz](#neleri-analiz-edebilirsiniz) · [Örnek çalışmalar](#örnek-çalışmalar) · [Sık sorulan sorular](#sık-sorulan-sorular) · [Belgeler](#belgeler)
[Hızlı başlangıç](#hızlı-başlangıç) · [REA nasıl çalışır](#rea-nasıl-çalışır) · [Neleri analiz edebilirsiniz](#neleri-analiz-edebilirsiniz) · [Örnek çalışmalar](#örnek-çalışmalar) · [Sık sorulan sorular](#sık-sorulan-sorular) · [GNU objdump ve Rizin araçları](../reverse-engineering-tools.md) · [Belgeler](#belgeler)
> [!IMPORTANT]
> REA’nın resmî kaynakları: [morluto/rea](https://github.com/morluto/rea), [rea.tools](https://rea.tools/), [rea-agents](https://www.npmjs.com/package/rea-agents) (npm).
> Kurulum ve sürüm bağlantılarını bu resmî kaynaklardan takip edin. Benzer bir depo adı veya kopyalanmış bir README, indirilen dosyanın resmî olduğunu kanıtlamaz.
<code>npx rea-agents setup</code>
@@ -137,6 +141,7 @@ REA; Node.js 22.x (>=22.19), 24.x (>=24.11) veya 26+ ve npm gerektirir. Ek araç
| Yerel makine kodu içeren ikili dosyalar | Sözde kod, assembly kodu, dizeler, semboller, çağrılar ve referanslar | Hopper, Ghidra veya IDA; [yerel kod analizi](https://rea.tools/tr/guides/native/) |
| Çevrimdışı ELF yapısı | Bölümler, segmentler, özgün semboller/yeniden konumlandırmalar ve statik analizden olası güvenlik önlemleri | Linux x64 üzerinde çağıranın sağladığı pwntools; [ikili dosya tanılama](../binary-diagnostics.md) |
| Go ikili dosyaları | Gömülü compiler sürümü, modüller, replacement'lar ve build ayarları | Yerleşik statik ELF/PE/thin Mach-O incelemesi; Go kurulumu gerekmez |
| Rust ikili dosyaları | Gömülü cargo-auditable crate adları, sürümleri, kaynakları ve bağımlılık ilişkileri | Yerleşik statik ELF/PE/thin Mach-O incelemesi; [Rust ikili dosyaları](../rust-binaries.md) |
| WASM artefaktı | Doğrulama, bölümler, tam import/export WAT biçimleri ve decode edilmiş WAT | Çağıranın sağladığı WABT 1.0.42; `inspect_wasm_artifact` |
| EVM bayt kodu | Yönlendirme seçicileri, bayt ofsetleri, çıkarımla belirlenen argümanlar ve durum değiştirilebilirliği | Linux x64 üzerinde yerel ham bayt/onaltılık girdi; [çevrimdışı EVM rehberi](../evm-bytecode.md) |
| SQLite veritabanları | Tablolar, sütunlar, index'ler, view'lar, trigger'lar ve seçilen sıradan tablo satırları | Yerel database/WAL snapshot'ı; native SQLite sınırlarıyla Node.js 24.x >=24.15 veya 26+ |
+6 -1
View File
@@ -19,7 +19,11 @@
**[Сайт](https://rea.tools/uk/) · [Посібники](https://rea.tools/uk/guides/) · [Приклади](https://rea.tools/uk/showcase/)**
[Швидкий старт](#швидкий-старт) · [Як працює REA](#як-працює-rea) · [Що можна аналізувати](#що-можна-аналізувати) · [Приклади](#приклади) · [Поширені запитання](#поширені-запитання) · [Документація](#документація)
[Швидкий старт](#швидкий-старт) · [Як працює REA](#як-працює-rea) · [Що можна аналізувати](#що-можна-аналізувати) · [Приклади](#приклади) · [Поширені запитання](#поширені-запитання) · [Інструменти GNU objdump і Rizin](../reverse-engineering-tools.md) · [Документація](#документація)
> [!IMPORTANT]
> Офіційні джерела REA: [morluto/rea](https://github.com/morluto/rea), [rea.tools](https://rea.tools/), [rea-agents](https://www.npmjs.com/package/rea-agents) (npm).
> Користуйтеся посиланнями на встановлення та випуски з цих офіційних джерел. Схожа назва репозиторію або скопійований README не підтверджують, що завантажуваний файл є офіційним.
<code>npx rea-agents setup</code>
@@ -135,6 +139,7 @@ REA потребує Node.js 22.x (>=22.19), 24.x (>=24.11) або 26+, а та
| Нативні бінарні файли | Псевдокод, асемблерний код, рядки, символи, виклики й посилання | Hopper, Ghidra або IDA; [нативний аналіз](https://rea.tools/uk/guides/native/) |
| Структура ELF без запуску | Секції, сегменти, початкові символи/релокації та можливі захисні механізми за даними статичного аналізу | pwntools, наданий стороною, що викликає інструмент, у Linux x64; [діагностика бінарних файлів](../binary-diagnostics.md) |
| Байт-код EVM | Селектори диспетчеризації, зміщення байтів, виведені припущення про аргументи та змінюваність стану | Локальні необроблені байти або шістнадцяткове представлення у Linux x64; [посібник EVM без запуску](../evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| Записані аварійні завершення в Linux | Необроблені записи note, регістри/сигнали кожного записаного потоку й необов'язкові кандидати зіставлення пам'яті | pwntools, наданий стороною, що викликає інструмент, у Linux x64; необов'язкові GDB/pwndbg; [записані аварійні завершення](../recorded-crashes.md) |
| JavaScript / Electron | Модулі, імпорти, карти вихідного коду, маршрути, IPC і зв'язки з нативними доповненнями | Node.js і npm; [аналіз застосунків](https://rea.tools/uk/guides/javascript/) |
| Сайти | Структура сторінки, скрипти, мережеві спостереження й запитані знімки екрана | Браузер сімейства Chrome; [аналіз браузера](https://rea.tools/uk/guides/browser/) |
+6 -1
View File
@@ -19,7 +19,11 @@
**[Trang web](https://rea.tools/vi/) · [Hướng dẫn](https://rea.tools/vi/guides/) · [Các nghiên cứu điển hình](https://rea.tools/vi/showcase/)**
[Bắt đầu nhanh](#bắt-đầu-nhanh) · [Cách REA hoạt động](#cách-rea-hoạt-động) · [Những gì bạn có thể phân tích](#những-gì-bạn-có-thể-phân-tích) · [Các nghiên cứu điển hình](#các-nghiên-cứu-điển-hình) · [Câu hỏi thường gặp](#câu-hỏi-thường-gặp) · [Tài liệu](#tài-liệu)
[Bắt đầu nhanh](#bắt-đầu-nhanh) · [Cách REA hoạt động](#cách-rea-hoạt-động) · [Những gì bạn có thể phân tích](#những-gì-bạn-có-thể-phân-tích) · [Các nghiên cứu điển hình](#các-nghiên-cứu-điển-hình) · [Câu hỏi thường gặp](#câu-hỏi-thường-gặp) · [Công cụ GNU objdump và Rizin](../reverse-engineering-tools.md) · [Tài liệu](#tài-liệu)
> [!IMPORTANT]
> Các nguồn chính thức của REA: [morluto/rea](https://github.com/morluto/rea), [rea.tools](https://rea.tools/), [rea-agents](https://www.npmjs.com/package/rea-agents) (npm).
> Hãy dùng các liên kết cài đặt và bản phát hành từ những nguồn chính thức này. Tên kho mã tương tự hoặc README được sao chép không chứng minh rằng tệp tải xuống là bản chính thức.
<code>npx rea-agents setup</code>
@@ -135,6 +139,7 @@ REA yêu cầu Node.js 22.x (>=22.19), 24.x (>=24.11) hoặc 26+, cùng với np
| Tệp nhị phân mã máy | Mã giả, hợp ngữ, chuỗi, ký hiệu, lời gọi và tham chiếu | Hopper, Ghidra hoặc IDA; [phân tích mã máy](https://rea.tools/vi/guides/native/) |
| Bố cục ELF ngoại tuyến | Các section, segment, ký hiệu/thông tin tái định vị gốc và các biện pháp giảm thiểu có thể có từ phân tích tĩnh | pwntools do bên gọi cung cấp trên Linux x64; [chẩn đoán tệp nhị phân](../binary-diagnostics.md) |
| Bytecode EVM | Bộ chọn điều phối, độ lệch byte, tham số suy luận và khả năng thay đổi trạng thái | Đầu vào cục bộ chứa byte thô hoặc dạng thập lục phân trên Linux x64; [hướng dẫn EVM ngoại tuyến](../evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| Sự cố Linux đã ghi lại | Bản ghi note thô, thanh ghi/tín hiệu của mọi luồng được ghi lại và các ứng viên ánh xạ tùy chọn | pwntools do bên gọi cung cấp trên Linux x64; GDB/pwndbg tùy chọn; [sự cố đã ghi lại](../recorded-crashes.md) |
| JavaScript / Electron | Mô-đun, các khai báo import, source map, tuyến, IPC và quan hệ với tiện ích mở rộng mã máy | Node.js và npm; [phân tích ứng dụng](https://rea.tools/vi/guides/javascript/) |
| Trang web | Cấu trúc trang, script, quan sát mạng và ảnh chụp màn hình được yêu cầu | Trình duyệt thuộc họ Chrome; [phân tích trình duyệt](https://rea.tools/vi/guides/browser/) |
+6 -1
View File
@@ -19,7 +19,11 @@
**[網站](https://rea.tools/zh-TW/) · [指南](https://rea.tools/zh-TW/guides/) · [案例](https://rea.tools/zh-TW/showcase/)**
[快速開始](#快速開始) · [REA 的工作原理](#rea-的工作原理) · [可以分析什麼](#可以分析什麼) · [案例](#案例) · [常見問題](#常見問題) · [文件](#文件)
[快速開始](#快速開始) · [REA 的工作原理](#rea-的工作原理) · [可以分析什麼](#可以分析什麼) · [案例](#案例) · [常見問題](#常見問題) · [GNU objdump 與 Rizin 工具](../reverse-engineering-tools.md) · [文件](#文件)
> [!IMPORTANT]
> REA 官方來源: [morluto/rea](https://github.com/morluto/rea), [rea.tools](https://rea.tools/), [rea-agents](https://www.npmjs.com/package/rea-agents) (npm).
> 請透過這些官方來源提供的安裝與發布連結取得 REA。相似的儲存庫名稱或複製的 README 不能證明下載內容來自官方。
<code>npx rea-agents setup</code>
@@ -139,6 +143,7 @@ REA 需要 Node.js 22.x(>=22.19)、24.x(>=24.11)或 26+,以及 npm。
| Go 二進位檔案 | 內嵌編譯器版本、模組、替換項和建置設定 | 內建靜態 ELF/PE/thin Mach-O 檢查;無需安裝 Go |
| WASM 工件 | 驗證、節、精確的匯入/匯出 WAT 形式及解碼後的 WAT | 呼叫方提供的 WABT 1.0.42;`inspect_wasm_artifact` |
| EVM 位元組碼 | 分派選擇器、位元組偏移、推斷的參數和狀態可變性 | Linux x64 上的本地原始位元組/十六進位輸入載體;[離線 EVM 指南](../evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| 已記錄的 Linux 崩潰 | 原始 note 記錄、每個已記錄執行緒的暫存器/訊號及可選的對映候選項 | Linux x64 上由呼叫方提供的 pwntools;可選的 GDB/pwndbg;[已記錄崩潰](../recorded-crashes.md) |
| JavaScript / Electron | 模組、匯入、source map、路由、IPC 和原生附加元件關係 | Node.js 和 npm;[應用分析](https://rea.tools/zh-TW/guides/javascript/) |
| 網站 | 頁面結構、腳本、網路觀察結果和按請求獲取的螢幕擷取畫面 | Chrome 系瀏覽器;[瀏覽器分析](https://rea.tools/zh-TW/guides/browser/) |
+6 -1
View File
@@ -19,7 +19,11 @@
**[网站](https://rea.tools/zh-CN/) · [指南](https://rea.tools/zh-CN/guides/) · [案例](https://rea.tools/zh-CN/showcase/)**
[快速开始](#快速开始) · [REA 的工作原理](#rea-的工作原理) · [可以分析什么](#可以分析什么) · [案例](#案例) · [常见问题](#常见问题) · [文档](#文档)
[快速开始](#快速开始) · [REA 的工作原理](#rea-的工作原理) · [可以分析什么](#可以分析什么) · [案例](#案例) · [常见问题](#常见问题) · [GNU objdump 和 Rizin 工具](../reverse-engineering-tools.md) · [文档](#文档)
> [!IMPORTANT]
> REA 官方来源: [morluto/rea](https://github.com/morluto/rea), [rea.tools](https://rea.tools/), [rea-agents](https://www.npmjs.com/package/rea-agents) (npm).
> 请通过这些官方来源提供的安装和发布链接获取 REA。相似的仓库名称或复制的 README 不能证明下载内容来自官方。
<code>npx rea-agents setup</code>
@@ -139,6 +143,7 @@ REA 需要 Node.js 22.x(>=22.19)、24.x(>=24.11)或 26+,以及 npm。
| Go 二进制文件 | 内嵌编译器版本、模块、替换项和构建设置 | 内置静态 ELF/PE/thin Mach-O 检查;无需安装 Go |
| WASM 工件 | 验证、节、精确的导入/导出 WAT 形式及解码后的 WAT | 调用方提供的 WABT 1.0.42;`inspect_wasm_artifact` |
| EVM 字节码 | 分派选择器、字节偏移、推断的参数和状态可变性 | Linux x64 上的本地原始字节/十六进制输入载体;[离线 EVM 指南](../evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| 已记录的 Linux 崩溃 | 原始 note 记录、每个已记录线程的寄存器/信号及可选的映射候选项 | Linux x64 上由调用方提供的 pwntools;可选的 GDB/pwndbg;[已记录崩溃](../recorded-crashes.md) |
| JavaScript / Electron | 模块、导入、source map、路由、IPC 和原生扩展关系 | Node.js 和 npm;[应用分析](https://rea.tools/zh-CN/guides/javascript/) |
| 网站 | 页面结构、脚本、网络观察结果和按请求获取的截图 | Chrome 系浏览器;[浏览器分析](https://rea.tools/zh-CN/guides/browser/) |
+81
View File
@@ -0,0 +1,81 @@
# Reverse-engineering tool integrations
REA can call caller-supplied GNU objdump, GDB, and Rizin installations. REA does not install or update these tools. Static objdump/Rizin workflows use the same services from CLI and MCP. GDB's persistent MCP sessions and ephemeral CLI command are available only on Linux. Persistent debugger sessions exist only for the lifetime of the REA MCP server process.
In a shared MCP server, unrestricted Rizin and Cutter commands, GDB console
commands, Rizin debugger start/close, and GDB debugger close retire any active
binary analysis session after the operation. This prevents a fresh analysis
provider from being rebound automatically while command effects may still be
writing. After the command and any background writers have stopped, call
`open_binary` explicitly before continuing analysis. A successful command
response alone does not prove that background writers have stopped. An active
Ghidra analysis session must be closed explicitly before an external mutation
can run.
## GNU objdump
`inspect_with_objdump` and `rea inspect-with-objdump` capture stdout and stderr as inline Evidence. Artifact inspection Evidence records SHA-256 digests before and after the provider call and whether those observed digests differ; this cannot prove the exact bytes consumed if the artifact changes during execution. Choose one artifact operation: `file_headers`, `section_headers`, `symbols`, `relocations`, `dwarf`, `disassemble`, or `disassemble_all`. `disassemble` maps to `-d`; `disassemble_all` maps to `-D` and has different symbol-boundary semantics. The pathless `inspect_with_objdump {"operation":"architectures"}` MCP call or `rea list-objdump-architectures` CLI command maps to `-i` and produces subjectless provider-capability Evidence describing BFD targets compiled into the installed binary, not a guarantee that a target is supported.
For DWARF, REA does not follow local debug links by default. Set `follow_debug_links` to `true` to pass `-WK`; external debug-file identities are not bound to Evidence when following links is enabled. The CLI option is `--follow-debug-links true`. REA clears `DEBUGINFOD_URLS` in the objdump child environment to disable debuginfod network access on GNU binutils versions that do not support `-WE`. The complete raw output is authoritative; REA does not normalize it into a version-independent disassembly schema.
```sh
rea inspect-with-objdump ./program disassemble
rea inspect-with-objdump ./program dwarf --follow-debug-links false
```
Captured stdout and stderr are retained up to a 16 MiB combined limit; `output_truncated` marks output beyond that limit.
## GDB
Persistent GDB sessions, including the MCP workflow and one-shot `rea debug-with-gdb` CLI, are available only on Linux. REA verifies a live inferior's output descriptors through `/proc` before detaching it; it does not claim equivalent descriptor verification on macOS. Windows is also unsupported because owned Job Object cleanup can terminate debugger inferiors. On supported Linux hosts, `start_gdb_session`, `gdb_console`, `gdb_session_status`, and `close_gdb_session` manage a persistent GDB/MI session in MCP. The one-shot CLI requires a caller-selected durable TTY: `rea debug-with-gdb --inferior-tty /dev/pts/7 'file ./program'`. The TTY must remain available after GDB exits so a detached inferior can continue writing. MCP starts GDB with `--nx --quiet --interpreter=mi3`, retries initialization with MI2 if MI3 initialization returns an error and cleanup succeeds, waits for its prompt, and disables auto-loading. Pass optional `inferior_tty` to select the terminal that future inferior runs use; REA configures it before the session becomes ready and checks the exact value with GDB/MI. `gdb_session_status` reports the selected path, whether REA still considers the configuration verified, and whether invalid UTF-8 has been observed in MI bytes (`mi_invalid_utf8`) or stderr (`stderr_invalid_utf8`). Commands that can change the inferior TTY or redirect a run revoke that verification permanently for the session, so close retains GDB ownership if a live inferior remains. Closing a session with one live inferior and a verified TTY automatically detaches the target, which can resume execution; MCP clients receive destructive-operation annotations for this behavior. The console remains unrestricted and can run shell commands, change target state, access files, and use network in the REA process user's security context. Raw MI records and console/target/log streams are returned with Evidence; command output is retained up to 16 MiB and explicitly marked when truncated.
Before a normal close, REA checks for live GDB thread groups. If one remains and a durable `inferior_tty` is verified, REA asks GDB to detach it and confirms the detach before stopping the debugger. Without that sink, select and apply a disposition to each inferior through `gdb_console` (for example, detach or kill as appropriate), then retry close. REA never infers target ownership from a PID or path. When the MCP server shuts down, REA terminates only its directly owned GDB process after confirming no inferior or a sink-backed detach; otherwise it retains the process and its output streams for retry.
```text
start_gdb_session {"inferior_tty":"/dev/pts/7"}
gdb_console {"session_id":"…","command":"file ./program"}
gdb_console {"session_id":"…","command":"info files"}
gdb_session_status {"session_id":"…"}
close_gdb_session {"session_id":"…"}
```
## Rizin
`start_rizin_debug_session` and `rea debug-with-rizin` require an explicit `inferior_tty` on Linux. Rizin launches the target with stdout and stderr routed to that caller-selected TTY and `dbg.exitkills=false`; the target can therefore continue running and writing to the TTY after REA closes the debugger. This is a visible target output effect, and the caller is responsible for selecting a suitable terminal that remains available. Before closing, REA serializes after the active command, parses the structured `olj` descriptor list, detaches only a unique `ptrace://` descriptor, confirms its absence, reads back `dbg.exitkills=false`, and verifies `/proc/<pid>/fd/1` and `/proc/<pid>/fd/2` still identify the selected TTY by device and inode. Any malformed or ambiguous readback keeps the Rizin session owned for retry. Persistent Rizin debugger sessions are unavailable outside Linux because this verification depends on `/proc`.
Persistent command Evidence retains the caller-selected and resolved startup paths in `parameters.launch_provenance`. These paths describe launch provenance, not the current target after unrestricted commands. `rizin_debug_session_status.output_invalid_utf8` reports whether lossy frame decoding has been observed during the session. Command Evidence sets `output_invalid_utf8` only when loss was observed in frames collected for that command, including retained partial output; earlier startup or command frames do not mark later valid output as lossy.
```sh
rea debug-with-rizin --inferior-tty /dev/pts/7 ./program dr
```
`execute_rizin_command` and `rea execute-rizin-command` run one selected command against a local artifact. The one-shot profile uses `-N -q -c`, suppressing user settings and scripts while leaving plugins available. Commands and plugins run with the REA process user's security context and may access files, the network, or perform other actions. REA preserves raw output and does not claim that command-specific JSON has one universal schema.
```sh
rea execute-rizin-command ./program iI
```
Captured stdout and stderr are retained up to a 16 MiB combined limit; `output_truncated` marks output beyond that limit.
## Cutter bridge
Cutter commands use the local REA Python bridge and authenticated loopback messages.
The client and plugin must support the current v2 handshake; older peers are
rejected before dispatch because they cannot preserve cross-caller recovery proof.
The client checks the final encoded request against the bridge's 16 MiB frame
limit before dispatch; an oversized command does not retain a cleanup owner.
Discovery admits at most 256 descriptor candidates and reads and probes at most
eight concurrently. A larger directory reports `bridge_directory_capacity_exceeded`.
Terminal receipts are recovered before another command, including from a new CLI
invocation. A signed status response also confirms completion of older bridge
connections after its UI dispatch, preserving recovery proof for a caller whose
receipt another caller has acknowledged. Neither receipt recovery nor a status
probe retries the original command. Failed acknowledgements remain pending and
block new commands until they can be retried successfully.
## Configuration and coverage
The optional `REA_OBJDUMP_COMMAND`, `REA_GDB_COMMAND`, and `REA_RIZIN_COMMAND` values select executable names or paths; otherwise REA searches `PATH`. Values are passed directly to process spawning, not expanded as shell command lines. Provider versions and capabilities remain unknown until observed from the installed tool and verified in the corresponding real-provider lane.
Provider capture limits are separate from the MCP response budget. A result that fits the provider limit may still exceed the default 10 MiB MCP response budget and return a transport `resource_constraint`. Configure `REA_MCP_MAX_RESPONSE_BYTES` to match a larger client receive buffer when that client supports one; otherwise use retained Evidence/export or complete CLI JSON output. See [MCP response limits](./mcp-contracts.md#tool-results).
+67
View File
@@ -0,0 +1,67 @@
# Rust binary dependency metadata
`inspect_rust_binary` / `inspect-rust-binary` answers which crate names,
versions, sources, and dependency edges are embedded by cargo-auditable in one
selected local executable or library. It reads the file without running it and
requires no Rust installation, active binary target, Hopper, Ghidra, or IDA.
```bash
rea inspect-rust-binary /absolute/path/to/application --json
```
The CLI resolves relative paths against the caller's working directory. MCP
requires an absolute filesystem path and preserves that exact selection:
```json
{
"name": "inspect_rust_binary",
"arguments": { "path": "/artifacts/application" }
}
```
## Observations
The inline Evidence result contains the artifact path, SHA-256, byte length,
container format, architecture, word size, and byte order. When a `.dep-v0`
section is present, `auditable_metadata` contains:
- `section_name`, `.dep-v0` for ELF and PE or `__DATA,.dep-v0` for thin Mach-O;
- `file_offset` and `section_bytes`, the exact file range of the compressed section;
- `compressed_bytes` and `uncompressed_bytes`;
- `format_version`, the embedded integer, or `null` when the field is omitted;
- `packages`, in the section's original order, with `name`, `version`, `source`,
`kind`, `dependencies`, and `root`;
- `root_package_index`, the single package marked `root`, or `null` when none is marked;
- `dependency_edges`, pairs of package indices in package-then-dependency order;
- `cyclic_dependency_indices`, sorted unique indices that participate in a cycle.
An omitted `kind` stays `null`. The embedded format treats that omission as
runtime, and that default is not stored in the section. An omitted dependency
list is an empty array. An omitted `root` flag is false.
`rustc_commit` is present only when a `/rustc/<40-hex>/` path is found in
read-only data. Its `evidence_kind` is `inferred`. The hash is not a claim that
that compiler produced the binary. Several distinct hashes leave a single
commit unknown.
## Limits and failures
The selected file is limited to 256 MiB. A dependency section is limited to 1
MiB compressed. Inflated JSON is limited to the smaller of 8 MiB and 64 times
the compressed size. The complete report is limited to 8 MiB. Empty sections,
truncated or trailing zlib bytes, invalid JSON, unknown fields, dependency
indices outside the package list, more than one root package, and compressed
dependency sections are typed failures. A cycle is reported and is not walked.
A missing section returns success with `auditable_metadata: null` and a
limitation. Absence of `.dep-v0` does not mean the binary has no dependencies.
Embedded names and versions are file content. They do not authenticate the
packages or the compiler.
Universal Mach-O containers are unsupported. Select a thin slice first. ELF,
PE, and thin Mach-O are the supported containers.
Package and dependency counts are checked against the minimum required JSON
representation before graph allocation or schema cloning. Oversized graphs
report the output byte budget; the compiler-path capacity reports
`maximum_rustc_hashes` in hashes, independently of byte limits.
+57 -5
View File
@@ -262,6 +262,24 @@ CI owns coverage; aggregate and domain/contract thresholds are maintained in
`vitest.config.ts`. They are glob-specific and never updated automatically.
Coverage does not replace named boundary or real-provider scenarios.
The `reverse-tools` commands run the focused tests and report coverage and
mutation results without an additional percentage requirement. Test failures,
invalid mutation configuration, and runner failures still fail the check.
Mutation targets cover reviewed production behavior, including signal-terminated
commands, Cutter descriptor identity, debugger cleanup ownership, GDB command
exit and cancellation, and Rizin startup, timeout Evidence, and process exit.
A second exhaustive pass runs the focused Cutter and Rizin timeout semantics tests against every compilable
selected mutant to avoid relying on per-test mutation coverage associations;
Stryker reports compile-error mutants separately because those cannot execute
tests. Both passes resolve named syntax owners, scoped declarations, guards,
callbacks, and reviewed expressions from the current TypeScript source; no
hand-maintained line ranges select mutations. Missing, ambiguous, or malformed
source targets stop configuration before mutation generation. The selections
retain their review scope rather than expanding to whole source files. The
focused suite also exercises affected MCP routes and the Python Cutter bridge.
Contract, integration, and real-provider lanes complement these focused tests;
simulated providers do not establish real-provider behavior.
CI runs six native Vitest shards without retries. Each shard emits a blob
report; the merge job produces JUnit and JSON diagnostics, a module timing
report, plus aggregate coverage during full qualification. It retains available
@@ -346,6 +364,17 @@ that explicit lane, not the routine iteration requirement.
## Real-toolchain verification lanes
Linux Rizin debugger ownership changes require a separate real-provider gate on
Rizin 0.7.4. Run
`npm run test:focused -- tests/boundary/providers/RizinInferiorTty.test.ts`.
This test verifies the caller-selected TTY against the actual inferior's file
descriptors, confirms `dbg.exitkills=false`, detaches through the `olj`/`o-`
protocol, and checks that the target survives debugger close and writes to the
selected TTY. The suite is included in the reverse-tools Vitest and mutation
typecheck selections; its real-provider assertions skip when Rizin 0.7.4 is
unavailable. Run the focused command above on a host with that provider for the
explicit real-provider verification gate.
Each real-toolchain command must require only the host tools needed to prove
its stated claim. Use a host-native fixture for host/provider acceptance, and
place optional cross-target formats or platform-specific runners in separate
@@ -887,8 +916,13 @@ successful ancestor push run of this CI workflow, rather than the preceding
push: changes from failed or cancelled intermediate runs remain in scope.
Missing, untrusted, or non-ancestor history selects every lane. The lookup is
bounded to the last 100 successful push runs; lookup failures broaden selection.
Every code change still runs all six portable shards, without coverage
instrumentation in this fast tier. This deliberately avoids relying on an
Every code change still selects all six portable shards, without coverage
instrumentation in this fast tier. Ordinary PR matrices cancel remaining
shards after the first failure; passing PRs execute the complete suite. Main,
`ci:full`, scheduled, manual, and release qualification retain every shard's
results after a failure. Available failed-shard reports remain diagnostic only:
failed, cancelled, skipped, or missing selected shards cannot pass the gate or
publish successful timing history. This deliberately avoids relying on an
import graph for generated files, filesystem inputs, subprocesses, or bridges.
Scheduled qualification is admitted hourly at minute 23. A forced full run at
@@ -916,10 +950,11 @@ classification job records its selection and broad-fallback reasons in the run
summary. Representative Git-diff cases live in
`tests/boundary/filesystem/ciChangeScope.test.ts`.
`CI required` always runs and checks classification and every selected lane,
`CI required` checks classification and every selected lane,
rejecting failed, cancelled, or unexpectedly skipped work. It rejects missing or
unknown tiers and requires every canonical scope to be explicitly `true` or
`false`; incomplete classification cannot silently omit verification lanes.
The aggregate remains cancellable so superseded runs release their slots.
Branch protection
should require this aggregate, `Static checks`, `Portable tests`, and
`Conventional PR title`. Title validation runs separately on PR opening,
@@ -968,7 +1003,7 @@ filename cases.
POSIX package verification resolves the runner's configured npm cache before
creating disposable client homes and passes that location to its child installs.
This reuses the download cache restored by `setup-node` while keeping client
This reuses the download cache restored by the shared npm-cache action while keeping client
configuration isolated. Installs retain their existing registry and integrity
checks.
@@ -998,7 +1033,24 @@ thresholds remain enforced in full qualification.
Missing or unusable history falls back to Vitest's default assignment. Only
timing data is reused; live provider results are never cached. Turbo outputs are
restored by task hash, with trusted default-branch runs as cache writers and PRs
as restore-only consumers. npm caches hold downloads, not `node_modules`.
as restore-only consumers. The static job also restores its Turbo snapshot;
each task revalidates its own input hash before reusing outputs or diagnostics.
The Node pin and npm install settings are global hash inputs. Knip includes its ignore rules and VitePress
entry, so changes to those inputs cannot reuse an older successful check.
The shared npm-cache action caches downloads, not `node_modules`, and every
consumer still runs `npm ci`. Keys cover the runner OS, actual Node architecture,
root lockfiles, and `.npmrc`. Only push, schedule, and manual events on the
repository's default branch may save shared npm caches; PRs restore only.
Static snapshots use the same write authority and are saved only after the
static job's validation succeeds. Main warms the new cache namespace after
merge; a cold cache or changed lockfile falls back to the normal install.
This prevents each PR from saving another branch-scoped copy of the same
download cache. It does not remove runner assignment waits.
Portable owner-based test selection remains observational. Its reports compare
proposed omissions with the full run; incomplete or skipped observations do not
establish that fewer tests would preserve regression detection.
The eight automatic browser, binary-layout, EVM, JavaScript-recovery,
recorded-crash, and web provider lanes download `rea-build-cache` from their own
+18 -3
View File
@@ -61,9 +61,24 @@ The tool profile preserves upstream release/source identity, resolved executable
paths, executable digests, exact banners and arguments. Executable digests are
checked again after each command. Caller-supplied tools are trusted programs;
version and digest recording are not publisher authentication or an OS sandbox.
Each subprocess has a 30-second deadline and 32 MiB combined output budget;
truncation fails. All commands use existing owned-process cancellation and
cleanup. Workspace cleanup failures remain explicit errors with resource paths.
Each subprocess has a 30-second deadline and 32 MiB combined output budget.
Inspection output past the budget fails with `resource_constraint`; an oversized
`--version` probe still reports `unreadable_output`. Both streams share the
budget, so a stream that starts after the other has filled it retains nothing.
The captured output keeps up to the first 4,096 bytes that each stream retained,
each stream's retained byte count, and the exit code and signal. Retained text
can end in U+FFFD where the budget cut a multi-byte character.
These excerpts bound the returned diagnostic text.
[PR #2117](https://github.com/morluto/rea/pull/2117) reports elapsed time, CPU
time, and peak process-family memory, including WABT children, for warm Linux
x64 WABT 1.0.42 CLI workflows; those costs did not change outside measurement
noise. Agent token usage and truly cold workflows remain
unmeasured. The underlying error cause still retains the full captured
subprocess snapshot, so the excerpt does not establish lower retained memory
or faster analysis.
All commands use existing owned-process cancellation and cleanup. Workspace
cleanup failures remain explicit errors with resource paths.
WAT is a decoded representation, not original source or proof of runtime
behavior. Custom annotations can preserve payloads, but WAT does not establish original
+20 -1
View File
@@ -224,6 +224,22 @@ are 0 and 50. The view groups request lines by method, WHATWG URL origin and
path template, sorted by origin, template and method. Query strings, fragments,
credentials, headers and bodies are not copied into groups.
Select `include_query_parameter_names: true` in the view to include distinct
observed query names per group. The default and explicit `false` omit the
`query_parameter_names` field. Selected groups include an array of
`{name, record_ordinals}` entries, sorted by Unicode code point; each name's
ordinals follow the parent's selected record order and occur once per record.
For `/products?category=books&page=1` and
`/products?category=games&sort=price`, names are `category`, `page` and `sort`.
Query values and fragments are not copied into this inventory.
Names use WHATWG `URLSearchParams` form-query decoding: literal `+` becomes
space, `%2B` becomes `+`, percent escapes decode as UTF-8, and empty names are
retained. Empty query pairs are ignored. Original URLs stay in parent Evidence;
name decoding does not normalize the recorded paths used for grouping.
The inventory describes observed names, without inferring required parameters,
value types or a complete API schema. Sensitive-parent refusals still apply.
| Rule | Exact segment format | Placeholder |
| ---------- | ---------------------------------------------------- | ------------ |
| `numeric` | ASCII digits only | `{numeric}` |
@@ -269,13 +285,16 @@ and validation scratch by walking the parent without cloning it. Inline requests
borrow the Evidence value through CLI/MCP envelope validation; the application
admits the entire portable envelope before authenticated parsing or hashing.
The envelope clone, hash scratch and capture clone stay charged during grouping.
Temporary URL/path/MIME work and retained state must
Temporary URL/path/MIME/query work and retained state must
fit together within a 96 MiB projection representation budget. A whole group or
merge is admitted before allocating its retained sets, map entries or array
values. Fixed group storage, distinct text, exclusions and limitations count as
well as matched segments. Per-record reservations are released after each
record; repeated values do not accumulate another retained charge. Only the
requested page is materialized as output groups.
Opt-in query projection reserves parser tuples and the per-record name set
before decoding, then admits distinct retained names and source ordinals before
changing a group. Repeated names within a request retain that ordinal once.
The representation budget uses conservative storage and worst-case JSON-escaping
allowances; it is not an enforced V8 heap or process-memory limit. It is separate
+7 -1
View File
@@ -9,6 +9,7 @@
"src/application/RealHopperAssertions.ts",
"scripts/verify/fridaBindingsCompatibility.ts",
"scripts/verify/termux/browser.mjs",
"scripts/verify-real-cutter.mjs",
"scripts/verify-real-ghidra-noreturn.mjs",
"tests/processOwnershipRunner.ts"
],
@@ -17,7 +18,12 @@
"entry": ["docs/.vitepress/config.ts"]
},
"ignoreBinaries": ["mkfifo"],
"ignoreDependencies": ["electron", "esbuild", "webpack"],
"ignoreDependencies": [
"@stryker-mutator/command-runner",
"electron",
"esbuild",
"webpack"
],
"ignoreExportsUsedInFile": true,
"rules": {
"files": "error",
File diff suppressed because it is too large Load Diff
+7 -11
View File
@@ -1,12 +1,12 @@
REA third-party npm runtime copyright, license and NOTICE texts
Collected from integrity-verified locked npm archives. Release-specific supplements and upstream notice gaps are identified in their entries.
External engines are separately obtained; see THIRD_PARTY_NOTICES.md.
Runtime dependency fingerprint (SHA-256): 63d5b55e027a0cfb3e77989ca337aca905f1652d10cfbfc4d4dd876d3ecd4f3a
Runtime dependency fingerprint (SHA-256): b0d0151958456c6e72c5720af80d783893be88a7b4c9a409db8505296fe10bd9
===== @babel/helper-string-parser@8.0.0 =====
===== @babel/helper-string-parser@8.0.6 =====
Declared license: MIT
Archive: https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.0.0.tgz
Integrity: sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg==
Archive: https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.0.6.tgz
Integrity: sha512-+6HYEBnsDRZHJtUTAEfMQd0zMDqdFHS7C+5vAsEZqBUr3vEMWOWlHJ0Jz1gS8jJIlCvLsuA6ivmeoqzH936YcA==
Scope: npm runtime dependency, including optional platform packages.
--- package/LICENSE ---
@@ -34,11 +34,10 @@ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
===== @babel/helper-validator-identifier@8.0.4 =====
===== @babel/helper-validator-identifier@8.0.6 =====
Declared license: MIT
Archive: https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.4.tgz
Integrity: sha512-4wFaiLd0bVo4cIoTXI3zKI038NIWE/cr3jvBjejOVYVxV/m8Ltav1USiGzG1fmS5J2RhgEOgXNNK46cRPnRsrg==
Archive: https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.6.tgz
Integrity: sha512-HYx0YmuchRxRSpnjvcNffnPS8DCauKNmnumIuHG3jnQAVewRA7kfJGwF13ayEpSZs7s4R/oBH4eppuXcAQd5JQ==
Scope: npm runtime dependency, including optional platform packages.
--- package/LICENSE ---
@@ -66,7 +65,6 @@ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
===== @babel/parser@8.0.4 =====
Declared license: MIT
Archive: https://registry.npmjs.org/@babel/parser/-/parser-8.0.4.tgz
@@ -8443,5 +8441,3 @@ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
+2 -1
View File
@@ -123,7 +123,8 @@ napi_value wrap(napi_env env, std::unique_ptr<Resource> resource);
Resource& resource(napi_env env, napi_value value, Kind kind);
std::unique_ptr<File> openFile(const std::wstring& path, DWORD access = GENERIC_READ,
bool directory = false);
bool directory = false,
DWORD finalSharing = FILE_SHARE_READ);
napi_value identity(napi_env env, HANDLE handle, const std::wstring& path);
std::unique_ptr<Runtime> createRuntime(const std::wstring& parent, const std::wstring& prefix);
void closeRuntime(Runtime& runtime);
+100 -2
View File
@@ -61,7 +61,8 @@ static Handle openComponent(const std::wstring& path, DWORD access, bool directo
return handle;
}
std::unique_ptr<File> openFile(const std::wstring& requested, DWORD access, bool directory) {
std::unique_ptr<File> openFile(const std::wstring& requested, DWORD access, bool directory,
DWORD finalSharing) {
auto result = std::make_unique<File>(localPath(requested));
result->requestedPath = requested;
const auto& path = result->path;
@@ -77,7 +78,8 @@ std::unique_ptr<File> openFile(const std::wstring& requested, DWORD access, bool
while (offset < path.size()) {
auto end = path.find(L'\\', offset);
const bool final = end == std::wstring::npos;
auto child = openComponent(path.substr(0, end), final ? access : 0, !final || directory);
auto child = openComponent(path.substr(0, end), final ? access : 0, !final || directory,
final ? finalSharing : FILE_SHARE_READ);
// Once the next component is pinned against deletion, its parent cannot
// become empty and NTFS cannot convert that parent into a reparse point.
// Relax only ancestor write sharing so unrelated child renames can proceed.
@@ -238,6 +240,100 @@ static void verifyPrivate(HANDLE handle, const std::wstring& path, bool root) {
require(user && system, "Private DACL must allow only current user and SYSTEM", path, ERROR_ACCESS_DENIED);
}
static std::unique_ptr<File> openPrivateBridgeDirectory(const std::wstring& path) {
// The retained runtime root handle carries DELETE authority for owned
// cleanup. Windows checks sharing in both directions, so this read-only
// inspection handle must share DELETE even though it requests no such right.
auto directory = openFile(path, FILE_LIST_DIRECTORY, true,
FILE_SHARE_READ | FILE_SHARE_DELETE);
verifyPrivate(directory->get(), path, true);
return directory;
}
static Handle openPrivateBridgeDescriptor(HANDLE parent, const std::wstring& name,
const std::wstring& path) {
require(!name.empty() && name.find_first_of(L"\\/:\"<>|?*") == std::wstring::npos &&
name != L"." && name != L".." && name.size() <= 255,
"Private descriptor requires one filename component", path, ERROR_INVALID_PARAMETER);
UNICODE_STRING coordinate{};
coordinate.Buffer = const_cast<wchar_t*>(name.data());
coordinate.Length = static_cast<USHORT>(name.size() * sizeof(wchar_t));
coordinate.MaximumLength = coordinate.Length;
OBJECT_ATTRIBUTES attributes;
InitializeObjectAttributes(&attributes, &coordinate, OBJ_CASE_INSENSITIVE, parent, nullptr);
IO_STATUS_BLOCK observation{};
HANDLE raw = INVALID_HANDLE_VALUE;
// Immutable runtime files retain their original writer handle so later
// opens cannot acquire write or delete access. This read-only handle must
// share those granted rights for Windows' symmetric share check to pass.
const auto status = NtCreateFile(&raw, GENERIC_READ | READ_CONTROL | FILE_READ_ATTRIBUTES | SYNCHRONIZE,
&attributes, &observation, nullptr, FILE_ATTRIBUTE_NORMAL,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_OPEN,
FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_REPARSE_POINT |
FILE_NON_DIRECTORY_FILE,
nullptr, 0);
if (status < 0)
throw Failure("Open Cutter bridge descriptor relative to its verified directory failed", path,
RtlNtStatusToDosError(status));
Handle descriptor(raw);
require(descriptor.valid() && observation.Information == FILE_OPENED,
"Cutter bridge descriptor was not opened as an existing file", path, ERROR_ACCESS_DENIED);
FILE_STANDARD_INFO standard{};
require(GetFileInformationByHandleEx(descriptor.get(), FileStandardInfo, &standard, sizeof(standard)),
"Read Cutter bridge descriptor metadata failed", path);
require(!standard.Directory && standard.EndOfFile.QuadPart >= 0 &&
standard.EndOfFile.QuadPart <= 64 * 1024,
"Cutter bridge descriptor exceeds its byte limit or is not a file", path, ERROR_FILE_TOO_LARGE);
FILE_ATTRIBUTE_TAG_INFO fileAttributes{};
require(GetFileInformationByHandleEx(descriptor.get(), FileAttributeTagInfo, &fileAttributes, sizeof(fileAttributes)),
"Read Cutter bridge descriptor attributes failed", path);
require((fileAttributes.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0,
"Cutter bridge descriptor cannot be a reparse point", path, ERROR_REPARSE_TAG_INVALID);
verifyPrivate(descriptor.get(), path, false);
return descriptor;
}
static napi_value verifyCutterBridgeDirectory(napi_env env, const std::vector<napi_value>& args) {
require(args.size() == 1, "Cutter bridge directory verification requires one path", L"",
ERROR_INVALID_PARAMETER);
const auto path = wide(env, args[0]);
const auto directory = openPrivateBridgeDirectory(path);
auto result = object(env);
set(env, result, "privateDacl", boolean(env, true));
set(env, result, "identity", identity(env, directory->get(), path));
return result;
}
static napi_value readCutterBridgeDescriptor(napi_env env, const std::vector<napi_value>& args) {
require(args.size() == 3, "Cutter bridge descriptor read requires directory, name, and byte limit", L"",
ERROR_INVALID_PARAMETER);
const auto path = wide(env, args[0]);
const auto name = wide(env, args[1]);
const double maximum = numeric(env, args[2]);
require(maximum >= 1 && maximum <= 64 * 1024 && maximum == static_cast<size_t>(maximum),
"Cutter bridge descriptor limit is outside the supported range", path, ERROR_INVALID_PARAMETER);
auto directory = openPrivateBridgeDirectory(path);
auto descriptor = openPrivateBridgeDescriptor(directory->get(), name, path + L"\\" + name);
FILE_STANDARD_INFO standard{};
require(GetFileInformationByHandleEx(descriptor.get(), FileStandardInfo, &standard, sizeof(standard)),
"Read Cutter bridge descriptor size failed", path);
require(standard.EndOfFile.QuadPart <= maximum,
"Cutter bridge descriptor exceeds the requested byte limit", path, ERROR_FILE_TOO_LARGE);
std::vector<unsigned char> bytes(static_cast<size_t>(standard.EndOfFile.QuadPart));
size_t offset = 0;
while (offset < bytes.size()) {
DWORD count = 0;
const DWORD requested = static_cast<DWORD>(std::min<size_t>(bytes.size() - offset, MAXDWORD));
require(ReadFile(descriptor.get(), bytes.data() + offset, requested, &count, nullptr) && count > 0,
"Read Cutter bridge descriptor through its verified handle failed", path);
offset += count;
}
napi_value result;
const void* source = bytes.empty() ? static_cast<const void*>("") : bytes.data();
check(napi_create_buffer_copy(env, bytes.size(), source, nullptr, &result));
return result;
}
std::unique_ptr<Runtime> createRuntime(const std::wstring& parentPath, const std::wstring& prefix) {
std::unique_ptr<File> parent;
try { parent = openFile(parentPath, 0, true); }
@@ -559,6 +655,8 @@ static napi_value snapshot(napi_env env, napi_value rootValue, Runtime& root,
}
napi_value filesystemCall(napi_env env, const std::wstring& operation, const std::vector<napi_value>& args) {
if (operation == L"cutter_bridge_verify_directory") return verifyCutterBridgeDirectory(env, args);
if (operation == L"cutter_bridge_read_descriptor") return readCutterBridgeDescriptor(env, args);
const auto expected = operation == L"open" || operation == L"close" || operation == L"runtime_close" || operation == L"runtime_snapshot_cancel" ? 1
: operation == L"runtime_create" || operation == L"runtime_mkdir" || operation == L"runtime_open" ? 2 : 3;
require(args.size() == static_cast<size_t>(expected), "Wrong native filesystem argument count", L"", ERROR_INVALID_PARAMETER);
+1
View File
@@ -464,6 +464,7 @@ napi_value inspect(napi_env env, std::unique_ptr<Runtime>& probe) {
set(env, result, "architecture", string(env, std::string("x64")));
set(env, result, "filesystem", filesystem);
set(env, result, "privateDacl", boolean(env, true));
set(env, result, "privateBridgeDescriptorAccess", boolean(env, true));
set(env, result, "atomicJobAssignment", boolean(env, true));
set(env, result, "killOnOwnerClose", boolean(env, true));
set(env, result, "protocolStdin", boolean(env, true));
+2006 -8
View File
File diff suppressed because it is too large Load Diff
+16 -2
View File
@@ -21,10 +21,14 @@
"mcp-server",
"model-context-protocol",
"static-analysis",
"disassembler",
"rea",
"decompiler",
"mcp",
"hopper"
"hopper",
"electron",
"javascript-analysis",
"ghidra",
"ida"
],
"publishConfig": {
"access": "public"
@@ -45,6 +49,7 @@
"dist",
"install.sh",
"bridge/hopper_bridge.py",
"bridge/cutter/rea_bridge.py",
"bridge/native/NativeUIChildren.swift",
"bridge/native/ReaNativeUI.swift",
"bridge/native/rea_lldb_tracer.py",
@@ -145,6 +150,10 @@
"test:integration": "vitest run --project boundary --project cli-boundary --project process-boundary --project mcp-boundary --project process-global --project acceptance",
"pretest:coverage": "npm run test:prepare",
"test:coverage": "vitest run --coverage.enabled --coverage.provider=v8",
"test:coverage:reverse-tools": "vitest run --config vitest.reverse-tools.config.ts --coverage.enabled",
"pretest:coverage:reverse-tools": "npm run test:prepare",
"test:mutation:reverse-tools": "node scripts/prepare-reverse-tools-mutation.mjs && stryker run stryker.config.mjs && stryker run stryker.semantics.config.mjs",
"pretest:mutation:reverse-tools": "npm run test:prepare",
"test:ci": "npm run test:coverage -- --reporter=default --reporter=junit --outputFile.junit=test-results.xml",
"pretest:ci:shard": "npm run test:prepare",
"test:ci:shard": "npm run test:ci:shard:run",
@@ -253,6 +262,7 @@
"build:windows-native": "node scripts/build-windows-native.mjs",
"verify:windows-native:artifact": "node scripts/verify-windows-native-artifact.mjs",
"prepublishOnly": "npm run verify:windows-native:artifact",
"verify:cutter": "npm run build:cached && node scripts/verify-real-cutter.mjs",
"verify:windows-native": "node scripts/verify-windows-native.mjs",
"verify:ghidra:windows:package": "node scripts/verify-packaged-ghidra-windows.mjs",
"build:ghidra:nativeaot": "node scripts/build-ghidra-nativeaot.mjs",
@@ -344,6 +354,9 @@
},
"devDependencies": {
"@fast-check/vitest": "0.5.0",
"@stryker-mutator/core": "10.0.0",
"@stryker-mutator/typescript-checker": "10.0.0",
"@stryker-mutator/vitest-runner": "10.0.0",
"@types/cross-spawn": "6.0.6",
"@types/node": "26.6.4",
"@types/semver": "7.7.1",
@@ -360,6 +373,7 @@
"turbo": "2.11.7",
"typescript": "7.0.2",
"typescript-termux": "npm:typescript@5.9.3",
"typescript6": "npm:typescript@6.0.3",
"vitepress": "1.6.4",
"vitest": "5.0.3"
},
+5
View File
@@ -62,6 +62,10 @@ function classifyPackage(base, head) {
]),
].filter((key) => beforeScripts?.[key] !== afterScripts?.[key]);
for (const script of changed) {
if (/^test:(coverage|mutation):reverse-tools$/.test(script)) {
selected.reverse_tools = true;
continue;
}
if (script === "test:sqlite" || script === "test:sqlite:run") {
selected.sqlite = true;
continue;
@@ -162,6 +166,7 @@ if (tier === "reused") {
.split("\0")
.filter(Boolean);
for (const file of files) {
if (matchesAny(file, SCOPES.reverse_tools)) selected.reverse_tools = true;
if (
/^(README(?:_[^/]+)?\.md|AGENTS\.md|CONTRIBUTING\.md|CHANGELOG\.md|SECURITY\.md|native\/windows\/README\.md|\.github\/pull_request_template\.md)$/.test(
file,
+1
View File
@@ -31,6 +31,7 @@ if (outputs.tier === "full" && selectedScopes.length !== CI_FLAGS.length)
const required = reused ? ["changes"] : ["changes", "static", "test"];
const lanes = {
code: ["build", "test-shard"],
reverse_tools: ["reverse-tools-quality"],
runtime: ["windows-native-build", "package-e2e"],
package: ["windows-curated"],
sqlite: ["sqlite-runtime"],
+56
View File
@@ -2,6 +2,62 @@
// Shared build inputs are classified once in plan.mjs rather than repeated in
// every workflow.
export const SCOPES = {
reverse_tools: [
"src/application/reverse/**",
"src/application/binary/BinarySession.ts",
"src/cutter/**",
"src/gdb/**",
"src/frida/frida-bindings.d.ts",
"src/objdump/**",
"src/cli/reverseEngineeringCommands.ts",
"src/process/ownedDebuggerSession.ts",
"src/rizin/**",
"src/contracts/*ToolContracts.ts",
"src/server/registerCutterTools.ts",
"src/server/externalMutationAdmission.ts",
"src/server/registerGdbTools.ts",
"src/server/registerReverseEngineeringTools.ts",
"src/server/providerEnvironment.ts",
"src/process/ExecFileOutput.ts",
"src/process/ExecFileOutput.test.ts",
"tests/composition/analysis-sessions/binarySession.test.ts",
"tests/boundary/filesystem/directAnalysisSnapshotReplay.test.ts",
"tests/boundary/filesystem/reverseToolsMutationConfig.test.ts",
"src/server/registerRizinDebugTools.ts",
"tests/boundary/providers/CutterBridge*.test.ts",
"tests/boundary/providers/cutterBridgeProducer.test.ts",
"tests/boundary/providers/GdbSession*.test.ts",
"tests/boundary/providers/GdbCommandQueue.test.ts",
"tests/boundary/providers/gdbTestHelpers.ts",
"tests/boundary/providers/RizinDebugSessionCoverage.part*.test.ts",
"tests/boundary/providers/RizinCommandTimeout.test.ts",
"tests/boundary/providers/RizinTimeoutEvidence.test.ts",
"tests/boundary/providers/RizinDebugSession*.test.ts",
"tests/boundary/providers/RizinInferiorTty.test.ts",
"tests/boundary/providers/RizinTestInferiorTty.ts",
"tests/boundary/process/ownedDebuggerSession.test.ts",
"tests/boundary/cli/gdbStartupCleanupCli.test.ts",
"tests/boundary/cli/reverseEngineeringCommands.test.ts",
"tests/boundary/mcp/cutter*.test.ts",
"tests/boundary/mcp/gdbCancellationMcp.test.ts",
"tests/boundary/mcp/debuggerCancellationMcp.test.ts",
"tests/boundary/mcp/rizinDebuggerCancellationMcp.test.ts",
"tests/boundary/mcp/reverseEngineeringPartialMcp.test.ts",
"tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts",
"tests/boundary/mcp/reverseEngineeringEnvironmentMcp.test.ts",
"tests/support/reverseEngineering*.ts",
"tests/support/ownedRizinCommandEvidenceTests.ts",
"tests/support/reverseDebuggerMcpTestHelpers.ts",
"tests/processOwnershipRunner.ts",
"tests/composition/reverseEngineering*.test.ts",
"vitest.reverse-tools.config.ts",
"vitest.reverse-tools-semantics.config.ts",
"stryker.config.mjs",
"stryker.semantics.config.mjs",
"tsconfig.reverse-tools-mutation.json",
"scripts/prepare-reverse-tools-mutation.mjs",
"scripts/lib/reverse-tools-mutation-targets.mjs",
],
// Apple artifact CLI/MCP lane on macOS, including its focused regressions.
apple: [
"src/native/Apple*",
+36
View File
@@ -19,6 +19,11 @@ export const toolFamilyCatalog = (sources) => {
contracts: [
...sources.nativeContracts.NATIVE_TOOL_CONTRACTS,
...sources.binaryDiagnosticsContracts.BINARY_DIAGNOSTICS_TOOL_CONTRACTS,
...sources.cutterContracts.CUTTER_TOOL_CONTRACTS,
...sources.reverseEngineeringContracts
.REVERSE_ENGINEERING_TOOL_CONTRACTS,
...sources.gdbContracts.GDB_TOOL_CONTRACTS,
...sources.rizinDebugContracts.RIZIN_DEBUG_TOOL_CONTRACTS,
],
},
{
@@ -28,6 +33,7 @@ export const toolFamilyCatalog = (sources) => {
...sources.artifactContracts.ARTIFACT_TOOL_CONTRACTS,
...sources.evmContracts.EVM_TOOL_CONTRACTS,
...sources.goContracts.GO_TOOL_CONTRACTS,
...sources.rustContracts.RUST_TOOL_CONTRACTS,
...sources.wasmContracts.WASM_TOOL_CONTRACTS,
...sources.sqliteContracts.SQLITE_TOOL_CONTRACTS,
...sources.captureContracts.CAPTURE_TOOL_CONTRACTS,
@@ -163,6 +169,32 @@ export const providerCatalog = (sources) => {
activeContracts,
} = electronContractSlices(sources);
return [
{
identity: sources.cutterProvider.CUTTER_PROVIDER_IDENTITY,
contracts: sources.cutterContracts.CUTTER_TOOL_CONTRACTS,
},
{
identity: sources.objdumpProvider.OBJDUMP_PROVIDER_IDENTITY,
contracts:
sources.reverseEngineeringContracts.REVERSE_ENGINEERING_TOOL_CONTRACTS.filter(
({ name }) => name === "inspect_with_objdump",
),
},
{
identity: sources.rizinProvider.RIZIN_PROVIDER_IDENTITY,
contracts:
sources.reverseEngineeringContracts.REVERSE_ENGINEERING_TOOL_CONTRACTS.filter(
({ name }) => name === "execute_rizin_command",
),
},
{
identity: sources.gdbProvider.GDB_PROVIDER_IDENTITY,
contracts: sources.gdbContracts.GDB_TOOL_CONTRACTS,
},
{
identity: sources.rizinDebugProvider.RIZIN_DEBUGGER_PROVIDER_IDENTITY,
contracts: sources.rizinDebugContracts.RIZIN_DEBUG_TOOL_CONTRACTS,
},
{
identity: sources.fridaProvider.FRIDA_PROVIDER_IDENTITY,
contracts: sources.fridaContracts.FRIDA_TOOL_CONTRACTS,
@@ -225,6 +257,10 @@ export const providerCatalog = (sources) => {
identity: sources.goProvider.GO_BINARY_PROVIDER_IDENTITY,
contracts: sources.goContracts.GO_TOOL_CONTRACTS,
},
{
identity: sources.rustProvider.RUST_BINARY_PROVIDER_IDENTITY,
contracts: sources.rustContracts.RUST_TOOL_CONTRACTS,
},
{
identity: sources.sqliteDomain.SQLITE_PROVIDER_IDENTITY,
contracts: sources.sqliteContracts.SQLITE_TOOL_CONTRACTS,
+12
View File
@@ -43,6 +43,16 @@ const SOURCE_PATHS = {
sessionContracts: "dist/contracts/sessionToolContracts.js",
binaryDiagnosticsContracts:
"dist/contracts/native/binaryDiagnosticsToolContracts.js",
cutterContracts: "dist/contracts/cutterToolContracts.js",
cutterProvider: "dist/cutter/CutterBridgeClient.js",
reverseEngineeringContracts:
"dist/contracts/reverseEngineeringToolContracts.js",
gdbContracts: "dist/contracts/gdbToolContracts.js",
gdbProvider: "dist/gdb/GdbSessionManager.js",
rizinDebugContracts: "dist/contracts/rizinDebugToolContracts.js",
objdumpProvider: "dist/objdump/ObjdumpCommand.js",
rizinProvider: "dist/rizin/RizinCommand.js",
rizinDebugProvider: "dist/rizin/RizinDebugSessionManager.js",
fridaContracts: "dist/contracts/fridaToolContracts.js",
fridaProvider: "dist/frida/FridaInstrumentationManager.js",
pwntoolsProvider: "dist/native/pwntools/PwntoolsRelease.js",
@@ -59,6 +69,8 @@ const SOURCE_PATHS = {
evmProvider: "dist/evm/EvmoleRelease.js",
goContracts: "dist/contracts/go/goToolContracts.js",
goProvider: "dist/go/GoBinaryProvider.js",
rustContracts: "dist/contracts/rust/rustToolContracts.js",
rustProvider: "dist/rust/RustBinaryProvider.js",
artifactContracts: "dist/contracts/artifactToolContracts.js",
managedContracts: "dist/contracts/managed/managedToolContracts.js",
firmwareContracts: "dist/contracts/firmware/firmwareToolContracts.js",
+1
View File
@@ -8,6 +8,7 @@ const MIGRATED_PROVIDER_ROOTS = new Set([
"sqlite",
"evm",
"go",
"rust",
"wasm",
"captures",
"signals",
@@ -0,0 +1,182 @@
import { readFileSync } from "node:fs";
import ts from "typescript6";
const compact = (text) => text.replace(/\s+/gu, "");
const nameOf = (node, source) => node.name?.getText(source);
const methodOwner = (node, source) => {
for (let parent = node; parent !== undefined; parent = parent.parent) {
if (ts.isMethodDeclaration(parent) || ts.isConstructorDeclaration(parent))
return {
owner: nameOf(parent.parent, source),
body: parent.body,
method: ts.isConstructorDeclaration(parent)
? "constructor"
: nameOf(parent, source),
};
}
return undefined;
};
const withinOwner = (node, selector, source) => {
if (selector.owner === undefined) return true;
const owner = methodOwner(node, source);
return (
owner?.owner === selector.owner &&
(selector.method === undefined || owner.method === selector.method)
);
};
const contains = (node, predicate) =>
predicate(node) ||
ts.forEachChild(node, (child) => contains(child, predicate)) === true;
const inBlockWithBinding = (node, binding) => {
if (binding === undefined) return true;
let block = node.parent;
while (block !== undefined && !ts.isBlock(block)) block = block.parent;
return block?.statements.some(
(statement) =>
ts.isVariableStatement(statement) &&
statement.declarationList.declarations.some(
(declaration) =>
ts.isIdentifier(declaration.name) &&
declaration.name.text === binding,
),
);
};
const isCommandHandler = (node, command) => {
if (!ts.isArrowFunction(node)) return false;
const property = node.parent;
if (
!ts.isPropertyAssignment(property) ||
!ts.isIdentifier(property.name) ||
property.name.text !== "run"
)
return false;
const call = property.parent.parent;
if (
!ts.isCallExpression(call) ||
!ts.isPropertyAccessExpression(call.expression) ||
!ts.isIdentifier(call.expression.expression) ||
call.expression.expression.text !== "cli" ||
call.expression.name.text !== "command"
)
return false;
const selected = call.arguments[0];
return (
selected !== undefined &&
ts.isPropertyAccessExpression(selected) &&
ts.isIdentifier(selected.expression) &&
selected.expression.text === "CLI_COMMANDS" &&
selected.name.text === command
);
};
const matches = (node, selector, source) => {
if (!withinOwner(node, selector, source)) return false;
if (
selector.direct === true &&
node.parent !== methodOwner(node, source)?.body
)
return false;
switch (selector.kind) {
case "expression":
return (
ts.isBinaryExpression(node) &&
compact(node.getText(source)) === compact(selector.text)
);
case "declaration":
return (
ts.isVariableDeclaration(node) &&
nameOf(node, source) === selector.name &&
inBlockWithBinding(node, selector.withinBlockWithBinding)
);
case "method":
return (
ts.isMethodDeclaration(node) && nameOf(node, source) === selector.name
);
case "constructor":
return ts.isConstructorDeclaration(node);
case "guard":
return (
ts.isIfStatement(node) &&
compact(node.expression.getText(source)) === compact(selector.condition)
);
case "call":
return (
ts.isCallExpression(node) &&
compact(node.expression.getText(source)) === compact(selector.callee) &&
(selector.event === undefined ||
(node.arguments[0] !== undefined &&
ts.isStringLiteral(node.arguments[0]) &&
node.arguments[0].text === selector.event))
);
case "try":
return (
ts.isTryStatement(node) &&
contains(node.tryBlock, (child) =>
selector.assignment !== undefined
? ts.isBinaryExpression(child) &&
child.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
ts.isIdentifier(child.left) &&
child.left.text === selector.assignment
: ts.isCallExpression(child) &&
compact(child.expression.getText(source)) ===
compact(selector.callee),
)
);
case "command-handler":
return isCommandHandler(node, selector.command);
default:
throw new Error(
`Unknown mutation selector kind: ${String(selector.kind)}`,
);
}
};
/** Parse a source once and resolve one owned region for every requested selector. */
export const mutationRanges = (path, selectors) => {
if (!Array.isArray(selectors) || selectors.length === 0)
throw new Error(`Mutation selectors must be nonempty: ${path}`);
for (const selector of selectors)
if (
["method", "constructor", "guard", "call", "try"].includes(
selector.kind,
) &&
typeof selector.owner !== "string"
)
throw new Error(
`Mutation selector requires a named class owner: ${path}`,
);
const source = ts.createSourceFile(
path,
readFileSync(path, "utf8"),
ts.ScriptTarget.Latest,
true,
);
if (source.parseDiagnostics.length !== 0)
throw new Error(
`Cannot select mutations from malformed TypeScript: ${path}`,
);
const found = selectors.map(() => []);
const visit = (node) => {
for (const [index, selector] of selectors.entries())
if (matches(node, selector, source)) found[index].push(node);
ts.forEachChild(node, visit);
};
visit(source);
return selectors.map((selector, index) => {
const candidates = found[index];
if (candidates.length !== 1)
throw new Error(
`Expected one mutation target in ${path}: ${JSON.stringify(selector)}; found ${candidates.length}`,
);
const node = candidates[0];
const first =
source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;
const last = source.getLineAndCharacterOfPosition(node.getEnd()).line + 1;
return `${path}:${first}-${last}`;
});
};
@@ -0,0 +1,19 @@
import { mkdir, rm, symlink } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const compiler = resolve(root, "node_modules/typescript6");
for (const packageName of ["core", "typescript-checker"]) {
const packagePath = resolve(
root,
"node_modules/@stryker-mutator",
packageName,
);
const nodeModulesPath = resolve(packagePath, "node_modules");
const typescriptPath = resolve(nodeModulesPath, "typescript");
await mkdir(nodeModulesPath, { recursive: true });
await rm(typescriptPath, { recursive: true, force: true });
await symlink(compiler, typescriptPath, "dir");
}
+23 -4
View File
@@ -1,12 +1,31 @@
/** Derive agent and Hopper setup support from the corresponding doctor checks. */
/**
* Host facts the packaged setup support is derived from.
*
* `linuxDistribution` is the distribution record the Hopper installer owner
* parses; it is absent when no distribution could be read, which leaves
* installer applicability unknown rather than unsupported.
*/
export interface SetupHostFacts {
readonly platform: NodeJS.Platform;
readonly linuxDistribution?: {
readonly hopperSetupSupported: boolean;
};
}
/**
* Derive agent setup support from the doctor node check and automated Hopper
* installer applicability from the facts their owners parse. Applicability is
* undefined when its owning fact is unavailable.
*/
export function packageSetupSupport(
checks:
| readonly { readonly name: string; readonly ok: boolean }[]
| undefined,
platform: NodeJS.Platform,
host: SetupHostFacts,
): {
supportedSetupHost: boolean;
hopperSetupSupported: boolean;
hopperReadinessRequired: boolean;
hopperSetupSupported: boolean | undefined;
};
/** Validate --help, --llms, and doctor output and determine host setup support. */
@@ -15,5 +34,5 @@ export function verifyPackageDiscovery(input: {
readonly environment: Readonly<Record<string, string | undefined>>;
}): Promise<{
supportedSetupHost: boolean;
hopperSetupSupported: boolean;
hopperSetupSupported: boolean | undefined;
}>;
+54 -12
View File
@@ -27,15 +27,56 @@ const REQUIRED_LLM_TOPICS = [
"analyze-javascript-application",
];
/** Derive agent and Hopper setup support from the corresponding doctor checks. */
export function packageSetupSupport(checks, platform) {
/**
* Derive agent setup support from the doctor node check and automated Hopper
* installer applicability from the facts their owners parse.
*
* Host readiness and installer applicability are different facts: a
* distribution REA supports can still be absent from the Hopper package's
* tested list, so the doctor host check cannot answer the second question.
* Applicability stays undefined when its owning fact is unavailable, which is
* distinct from a host known to lack an automated installer.
*/
export function packageSetupSupport(checks, host) {
const supportedSetupHost =
checks?.find(({ name }) => name === "node")?.ok === true;
const hopperSetupSupported =
supportedSetupHost &&
checks?.find(({ name }) => name === "host")?.ok === true &&
platform !== "win32";
return { supportedSetupHost, hopperSetupSupported };
const hopperReadinessRequired =
host.platform !== "win32" &&
checks?.find(({ name }) => name === "host")?.ok === true;
return {
supportedSetupHost,
hopperReadinessRequired,
hopperSetupSupported: hopperInstallerSupported(
host,
checks?.find(({ name }) => name === "host")?.ok,
),
};
}
/**
* Whether `rea setup --install-hopper` can install Hopper automatically here.
* On macOS the doctor host check already is the owner's installer predicate
* (macOS 12 or later); on Linux it reports REA host support instead, so the
* distribution's own parsed applicability governs.
*/
function hopperInstallerSupported(host, hostCheckOk) {
if (host.platform === "win32") return false;
if (host.platform === "linux")
return host.linuxDistribution?.hopperSetupSupported;
return hostCheckOk;
}
/**
* The distribution facts the Hopper installer owner parses, taken from the
* built application so the verifier follows the predicate the package ships.
* Loaded only where a distribution can exist, which also keeps the derivation
* above testable without a build.
*/
async function readHostLinuxDistribution() {
if (process.platform !== "linux") return undefined;
const { readLinuxDistribution } =
await import("../dist/application/LinuxHopper.js");
return readLinuxDistribution();
}
/** Validate --help, --llms, and doctor output and determine host setup support. */
@@ -48,10 +89,11 @@ export async function verifyPackageDiscovery({ cli, environment }) {
environment,
);
const doctor = json(doctorExecution.stdout);
const { supportedSetupHost, hopperSetupSupported } = packageSetupSupport(
doctor.checks,
process.platform,
);
const { supportedSetupHost, hopperReadinessRequired, hopperSetupSupported } =
packageSetupSupport(doctor.checks, {
platform: process.platform,
linuxDistribution: await readHostLinuxDistribution(),
});
const hopperReady = doctor.checks?.find(({ name }) => name === "hopper")?.ok;
const expectedDoctorHealth = doctor.checks?.every(({ ok }) => ok) === true;
const missingHelp = REQUIRED_HELP_COMMANDS.filter(
@@ -65,7 +107,7 @@ export async function verifyPackageDiscovery({ cli, environment }) {
missingLlms.length !== 0 ||
doctor.healthy !== expectedDoctorHealth ||
doctorExecution.status !== (expectedDoctorHealth ? 0 : 1) ||
(hopperSetupSupported && hopperReady !== true)
(hopperReadinessRequired && hopperReady !== true)
)
throw new Error(
`packaged CLI discovery or doctor failed: ${JSON.stringify({ helpSetup: help.includes("setup"), llmsDecompile: llms.includes("decompile"), doctor })}`,
+6
View File
@@ -8,4 +8,10 @@ export function assertLinuxPackageProviderFailure(execution: {
export function verifyPackagePlatform(input: {
readonly cli: string;
readonly environment: Readonly<Record<string, string | undefined>>;
readonly platform?: string;
readonly runCommand?: (
command: string,
arguments_: readonly string[],
environment: Readonly<Record<string, string | undefined>>,
) => Promise<string>;
}): Promise<void>;
+29 -15
View File
@@ -1,8 +1,13 @@
import { json, run, runWithStatus } from "./lib/verify-package-core.mjs";
/** Run platform-specific deep-analysis smoke tests. */
export async function verifyPackagePlatform({ cli, environment }) {
if (process.platform === "linux") {
export async function verifyPackagePlatform({
cli,
environment,
platform = process.platform,
runCommand = run,
}) {
if (platform === "linux") {
const unsupportedExecution = await runWithStatus(
cli,
["analyze", process.execPath, "--json"],
@@ -11,25 +16,27 @@ export async function verifyPackagePlatform({ cli, environment }) {
assertLinuxPackageProviderFailure(unsupportedExecution);
} else {
const overview = json(
await run(cli, ["analyze", process.execPath, "--json"], environment),
await runCommand(
cli,
["analyze", process.execPath, "--json"],
environment,
),
);
if (
overview.operation !== "binary_overview" ||
overview.normalized_result?.procedure_count < 1
)
if (!hasPositiveProcedureCount(overview))
throw new Error(
`packaged Hopper-backed analyze CLI failed: ${JSON.stringify(overview)}`,
);
const inspected = json(
await run(cli, ["inspect", process.execPath, "--json"], environment),
await runCommand(
cli,
["inspect", process.execPath, "--json"],
environment,
),
);
if (
inspected.operation !== "binary_overview" ||
inspected.normalized_result?.procedure_count < 1
)
if (!hasPositiveProcedureCount(inspected))
throw new Error("packaged inspect CLI failed");
const functionResult = json(
await run(
await runCommand(
cli,
["function", process.execPath, "0x1000", "--json"],
environment,
@@ -44,7 +51,7 @@ export async function verifyPackagePlatform({ cli, environment }) {
`packaged function CLI failed: ${JSON.stringify(functionResult)}`,
);
const xrefs = json(
await run(
await runCommand(
cli,
["xrefs", process.execPath, "0x1000", "--json"],
environment,
@@ -56,7 +63,7 @@ export async function verifyPackagePlatform({ cli, environment }) {
)
throw new Error(`packaged xrefs CLI failed: ${JSON.stringify(xrefs)}`);
const trace = json(
await run(
await runCommand(
cli,
["trace", process.execPath, "fixture", "--json"],
environment,
@@ -93,3 +100,10 @@ export const assertLinuxPackageProviderFailure = (execution) => {
`packaged Linux Hopper verification did not fail closed: ${JSON.stringify(failure)}`,
);
};
const hasPositiveProcedureCount = (result) =>
typeof result === "object" &&
result !== null &&
result.operation === "binary_overview" &&
Number.isInteger(result.normalized_result?.procedure_count) &&
result.normalized_result.procedure_count > 0;
+2 -3
View File
@@ -356,9 +356,8 @@ const verifySetupApply = async ({
hopperSetupSupported,
}) => {
const status = "ready";
const hopperStatus = hopperSetupSupported
? "needs_confirmation"
: "needs_human";
const hopperStatus =
hopperSetupSupported === true ? "needs_confirmation" : "needs_human";
const firstExecution = await runWithStatus(
cli,
["setup", "--yes", "--all-detected", "--json"],
+2
View File
@@ -4,6 +4,7 @@ import { promisify } from "node:util";
const exec = promisify(execFile);
const packedHopperBridge = "package/bridge/hopper_bridge.py";
const packedCutterBridge = "package/bridge/cutter/rea_bridge.py";
const packedGhidraBridge = "package/bridge/ghidra/ReaGhidraBridge.java";
const packedGhidraActivator =
"package/bridge/ghidra/ReaGhidraBundleActivator.java";
@@ -12,6 +13,7 @@ const packedGhidraActivator =
export async function verifyPackedBridge({ workspace, tarball, packedFiles }) {
for (const path of [
packedHopperBridge,
packedCutterBridge,
packedGhidraBridge,
packedGhidraActivator,
]) {
+214
View File
@@ -0,0 +1,214 @@
#!/usr/bin/env node
import assert from "node:assert/strict";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { execFile } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
import {
access,
constants,
mkdtemp,
readFile,
rm,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { promisify } from "node:util";
import { createServer } from "../dist/server/createServer.js";
const execFileAsync = promisify(execFile);
const cli = resolve("scripts/rea.mjs");
const runCli = async (...arguments_) => {
const { stdout } = await execFileAsync(
process.execPath,
[cli, ...arguments_, "--format", "json"],
{
encoding: "utf8",
maxBuffer: 4 * 1024 * 1024,
env: process.env,
},
);
return JSON.parse(stdout);
};
const projectRoot = await mkdtemp(join(tmpdir(), "rea-cutter-smoke-"));
const projectPath = join(projectRoot, "smoke.rzdb");
const rizinQuote = (value) =>
`"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
const unavailableAnalysis = {
execute: async () => {
throw new Error(
"The Cutter verification does not call unrelated analysis tools.",
);
},
};
const expectedPlatform = {
Linux: "linux",
macOS: "darwin",
Windows: "win32",
}[process.env.EXPECTED_PLATFORM];
if (expectedPlatform !== undefined)
assert.equal(
process.platform,
expectedPlatform,
"Cutter runner did not match its declared platform.",
);
try {
const discovery = await runCli("list-cutter-sessions");
assert.equal(
discovery.discovery_status,
"sessions_found",
"Open upstream Cutter with the REA plugin before running this smoke test.",
);
assert.ok(discovery.sessions.length > 0);
const session = discovery.sessions[0];
assert.ok(session);
assert.ok(
session.cutter_version,
"The upstream Cutter API did not report its version.",
);
if (process.env.REA_CUTTER_EXPECTED_VERSION !== undefined)
assert.ok(
session.cutter_version.includes(process.env.REA_CUTTER_EXPECTED_VERSION),
"The live Cutter version did not match the configured version.",
);
assert.ok(
session.current_file,
"Open a disposable local binary in Cutter before running this smoke test.",
);
const artifactPath = session.current_file;
const artifactDigest = createHash("sha256")
.update(await readFile(artifactPath))
.digest("hex");
const inspection = await runCli(
"cutter-command",
session.session_id,
String(session.document_generation),
"ij",
"--json",
);
assert.equal(inspection.predicate_type, "rea.cutter.command-observation");
assert.ok(
Object.hasOwn(inspection, "raw_result"),
"Cutter ij result was not retained as Evidence.",
);
assert.equal(typeof inspection.raw_result.bin?.arch, "string");
const mcpServer = createServer(
{ kind: "fixed", analysis: unavailableAnalysis },
{
providerEnvironment: process.env,
},
);
const mcpClient = new Client({
name: "rea-cutter-upstream-smoke",
version: "1",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await mcpServer.connect(serverTransport);
await mcpClient.connect(clientTransport);
const mcpDiscovery = await mcpClient.callTool({
name: "list_cutter_sessions",
arguments: {},
});
assert.notEqual(mcpDiscovery.isError, true);
assert.equal(
mcpDiscovery.structuredContent.discovery_status,
"sessions_found",
);
const mcpInspection = await mcpClient.callTool({
name: "cutter_command",
arguments: {
session_id: session.session_id,
expected_generation: session.document_generation,
command: "ij",
json: true,
},
});
assert.notEqual(mcpInspection.isError, true);
assert.deepEqual(
mcpInspection.structuredContent.normalized_result,
inspection.normalized_result,
"Cutter CLI and MCP returned different analysis results.",
);
} finally {
await mcpClient.close();
await mcpServer.close();
}
const annotation = `rea-smoke-${randomUUID()}`;
await runCli(
"cutter-command",
session.session_id,
String(session.document_generation),
`CC ${annotation} @ entry0`,
);
await runCli(
"cutter-command",
session.session_id,
String(session.document_generation),
`Ps ${rizinQuote(projectPath)}`,
);
await access(projectPath, constants.R_OK | constants.W_OK);
await runCli(
"cutter-command",
session.session_id,
String(session.document_generation),
"CC- @ entry0",
);
const removed = await runCli(
"cutter-command",
session.session_id,
String(session.document_generation),
"CC. @ entry0",
);
assert.ok(
!String(removed.raw_result).includes(annotation),
"The in-memory annotation was not removed before project reopening.",
);
await runCli(
"cutter-command",
session.session_id,
String(session.document_generation),
`Po ${rizinQuote(projectPath)}`,
);
const recovered = await runCli(
"cutter-command",
session.session_id,
String(session.document_generation),
"CC. @ entry0",
);
assert.equal(recovered.predicate_type, "rea.cutter.command-observation");
assert.ok(
String(recovered.raw_result).includes(annotation),
"The saved project did not preserve the analysis comment after reopening.",
);
const finalArtifactDigest = createHash("sha256")
.update(await readFile(artifactPath))
.digest("hex");
assert.equal(
finalArtifactDigest,
artifactDigest,
"Cutter project edits changed the executable bytes.",
);
const report = {
ok: true,
platform: process.platform,
cutter_version: session.cutter_version,
document_generation: session.document_generation,
cli_mcp_evidence_parity: true,
annotation_saved_and_reopened: true,
executable_digest_unchanged: true,
};
await writeFile("cutter-smoke.json", `${JSON.stringify(report, null, 2)}\n`, {
mode: 0o600,
});
console.log(JSON.stringify(report));
} finally {
await rm(projectRoot, { recursive: true, force: true });
}
+52 -18
View File
@@ -276,12 +276,41 @@ try {
)
).stdout.split(/\r?\n/);
if (nativeHelp.at(-1) === "") nativeHelp.pop();
const nativeCatalogText = (
await execute(
process.env.REA_SIGROK_COMMAND,
["--dont-scan", "--list-supported"],
{ env: environment, timeout: 30000, maxBuffer: 4 * 1024 * 1024 },
)
).stdout;
const catalogHeading = "Supported protocol decoders:\n";
assert.ok(nativeCatalogText.includes(catalogHeading));
// Independent native-output oracle, without importing the production parser.
const nativeCatalog = nativeCatalogText
.split(catalogHeading)[1]
.trim()
.split("\n")
.map((line) => {
const record = line.trimStart();
const separator = record.indexOf(" ");
assert.ok(separator > 0);
return {
id: record.slice(0, separator),
name: record.slice(separator).trimStart(),
};
});
assert.ok(nativeCatalog.length > 0);
for (const input of [
{ query: "uart" },
{},
{ query: "UaRt" },
{ limit: 1 },
{ offset: 1, limit: 2 },
{ limit: null },
{ offset: nativeCatalog.length, limit: 2 },
{ decoder: "uart" },
{ decoder: "uart", query: "BaUd" },
{ decoder: "uart", offset: 50, limit: null },
{ decoder: "uart", query: "[" },
{ query: "rea_no_such_decoder" },
]) {
const started = performance.now();
@@ -306,23 +335,28 @@ try {
JSON.stringify(response),
),
});
if (input.decoder) {
const matched = nativeHelp
.map((text, i) => ({ line_number: i + 1, text }))
.filter(({ text }) =>
text.toLowerCase().includes((input.query ?? "").toLowerCase()),
);
assert.deepEqual(
report.help_lines,
matched.slice(
input.offset ?? 0,
input.limit === null
? undefined
: (input.offset ?? 0) + (input.limit ?? 50),
),
);
} else if (input.query === "uart")
assert.ok(report.decoders.some(({ id }) => id === "uart"));
const nativeRecords = input.decoder
? nativeHelp.map((text, i) => ({ line_number: i + 1, text }))
: nativeCatalog;
const matched = nativeRecords.filter((record) =>
("text" in record ? record.text : `${record.id} ${record.name}`)
.toLowerCase()
.includes((input.query ?? "").toLowerCase()),
);
const offset = input.offset ?? 0;
const page = matched.slice(
offset,
input.limit === null ? undefined : offset + (input.limit ?? 50),
);
assert.deepEqual(input.decoder ? report.help_lines : report.decoders, page);
assert.deepEqual(input.decoder ? report.decoders : report.help_lines, []);
assert.deepEqual(report.output_window, {
unit: input.decoder ? "help-lines" : "decoders",
examined: nativeRecords.length,
matching: matched.length,
returned: page.length,
has_more: offset + page.length < matched.length,
});
const flags = Object.entries(input).flatMap(([key, value]) =>
value === null ? ["--all"] : [`--${key}`, String(value)],
);
+39 -10
View File
@@ -190,12 +190,21 @@ try {
const candidate = join(candidateRoot, "module.wasm");
await writeFile(join(candidateRoot, "source.wat"), "(module (memory 2))");
await tool("wat2wasm", ["source.wat", "-o", "module.wasm"], candidateRoot);
const glue = join(fixtureRoot, "glue.js");
await writeFile(
glue,
'fetch("./module.wasm"); new URL("https://example.invalid/module.wasm?version=1", import.meta.url);',
const glueSource =
'fetch("./module.wasm"); new URL("https://example.invalid/module.wasm?version=1", import.meta.url);';
const glueSources = [
glueSource,
`\uFEFF${glueSource}`,
`\uFEFF\n${glueSource}`,
`#!/usr/bin/env node\n${glueSource}`,
`\uFEFF#!/usr/bin/env node\n${glueSource}`,
];
const gluePaths = glueSources.map((_, index) =>
join(fixtureRoot, `glue-${index}.js`),
);
const input = { path, glue_paths: [glue], candidate_paths: [candidate] };
for (const [index, gluePath] of gluePaths.entries())
await writeFile(gluePath, glueSources[index]);
const input = { path, glue_paths: gluePaths, candidate_paths: [candidate] };
assert.ok(ajv.validate(advertised.inputSchema, input));
const cliValue = await inspectCli(input);
assert.equal(cliValue.category, undefined, JSON.stringify(cliValue));
@@ -219,11 +228,31 @@ try {
assert.equal(report.wat.sha256, sha256(wat));
assert.equal(report.headers, `${headers}\n`);
assert.equal(report.details, details.slice(1));
assert.equal(report.glue[0].artifact.sha256, sha256(await readFile(glue)));
assert.deepEqual(
report.glue[0].references.map(({ candidate_paths }) => candidate_paths),
[[path], [path, candidate]],
);
assert.equal(report.glue.length, glueSources.length);
for (const [index, source] of glueSources.entries()) {
const observed = report.glue[index];
assert.equal(observed.artifact.path, gluePaths[index]);
assert.equal(observed.artifact.sha256, sha256(source));
assert.equal(observed.artifact.bytes, Buffer.byteLength(source));
assert.equal(await readFile(gluePaths[index], "utf8"), source);
assert.equal(observed.parse_status, "complete");
assert.deepEqual(
observed.references.map(({ candidate_paths }) => candidate_paths),
[[path], [path, candidate]],
);
assert.deepEqual(
observed.references.map(({ line, column }) => ({ line, column })),
["./module.wasm", "https://example.invalid/module.wasm?version=1"].map(
(value) => {
const offset = source.indexOf(`"${value}"`);
return {
line: source.slice(0, offset).split("\n").length,
column: offset - source.lastIndexOf("\n", offset) - 1,
};
},
),
);
}
assert.notEqual(report.candidates[0].sha256, report.candidates[1].sha256);
for (const command of report.tool_profile.commands)
assert.equal(command.sha256, sha256(await readFile(command.path)));
+49
View File
@@ -148,6 +148,10 @@ process.stdout.write(JSON.stringify({executable:basename(process.execPath),abiVe
"//localhost/share/target.bin",
])
assert.throws(() => native.call("open", [rejected]));
assert.throws(
() => native.call("cutter_bridge_verify_directory", [sourceDirectory]),
/owner|DACL/u,
);
report.controls.ordinaryDriveSeparatorsAndRequestedIdentity = true;
// An owned runtime's DELETE lease conflicts with a fresh parent admission.
// This produces a genuine sharing failure after successful authority caching,
@@ -282,6 +286,10 @@ process.stdout.write(JSON.stringify({executable:basename(process.execPath),abiVe
() => native.call("open", [join(junction, "target.bin")]),
/Reparse/u,
);
assert.throws(
() => native.call("cutter_bridge_verify_directory", [junction]),
/Reparse/u,
);
assert.throws(() => native.call("open", [source + ":stream"]));
const runtime = native.call("runtime_create", [
workspace.replaceAll("\\", "/"),
@@ -326,6 +334,47 @@ process.stdout.write(JSON.stringify({executable:basename(process.execPath),abiVe
"descriptor.json",
Buffer.from("fixture"),
]);
assert.equal(
native.call("cutter_bridge_verify_directory", [runtime.path]).privateDacl,
true,
);
assert.equal(
native
.call("cutter_bridge_read_descriptor", [
runtime.path,
"descriptor.json",
64 * 1024,
])
.toString("utf8"),
"fixture",
);
const descriptorJunction = join(runtime.path, "descriptor-link.json");
await symlink(sourceDirectory, descriptorJunction, "junction");
assert.throws(() =>
native.call("cutter_bridge_read_descriptor", [
runtime.path,
"descriptor-link.json",
64 * 1024,
]),
);
assert.throws(
() =>
native.call("cutter_bridge_read_descriptor", [
runtime.path,
"descriptor.json",
3,
]),
/byte limit/u,
);
assert.throws(
() =>
native.call("cutter_bridge_read_descriptor", [
runtime.path,
"..\\escape.json",
64 * 1024,
]),
/filename component/u,
);
assert.throws(() =>
native.call("runtime_write", [
runtime.handle,
+2 -4
View File
@@ -1707,9 +1707,7 @@ export class AdbProvider {
},
provider,
{
limitations: [
"Push writes the caller's file to the device; this is the only device-mutating ADB tool",
],
limitations: ["Push writes the caller's file to the device"],
},
),
);
@@ -1731,7 +1729,7 @@ export class AdbProvider {
{
limitations: [
"The device did not answer sha256sum, so the transfer is not device-side verified",
"Push writes the caller's file to the device; this is the only device-mutating ADB tool",
"Push writes the caller's file to the device",
],
},
),
+95 -3
View File
@@ -40,10 +40,14 @@ import {
} from "../domain/zipPackageFormat.js";
import {
parseCodeViewData,
parseExecutableHeader,
parsePeRecord,
peDebugDirectoryEntry,
peRvaToFileOffset,
type ExecutableMetadata,
} from "../domain/binaryTarget.js";
import type { PeCodeViewRecord } from "../domain/binaryTargetTypes.js";
/** Options for resolving a local binary target and its stable identity. */
export interface BinaryTargetResolverOptions {
@@ -549,10 +553,98 @@ const readPeMetadata = async (
return err(`unsupported ${windowsHeader.signature} executable in MZ image`);
const optionalHeaderSize = fileHeader.readUInt16LE(20);
if (optionalHeaderSize > 4096) return err("invalid PE optional header size");
const numberOfSections = fileHeader.readUInt16LE(6);
const record = Buffer.alloc(24 + optionalHeaderSize);
const recordRead = await handle.read(record, 0, record.length, offset);
throwIfTargetResolutionCancelled(signal);
return recordRead.bytesRead === record.length
? parsePeRecord(record)
: err("invalid or truncated PE header");
if (recordRead.bytesRead !== record.length)
return err("invalid or truncated PE header");
const codeView = await readPeCodeView(
handle,
offset,
numberOfSections,
record.subarray(24),
optionalHeaderSize,
signal,
);
return parsePeRecord(record, codeView);
};
const readPeCodeView = async (
handle: FileHandle,
peOffset: number,
numberOfSections: number,
optionalHeader: Buffer,
optionalHeaderSize: number,
signal?: AbortSignal,
): Promise<PeCodeViewRecord | undefined> => {
throwIfTargetResolutionCancelled(signal);
const debugDir = peDebugDirectoryEntry(optionalHeader);
if (debugDir === undefined || numberOfSections > 96) return undefined;
const sectionTableOffset = peOffset + 24 + optionalHeaderSize;
const sectionTableSize = numberOfSections * 40;
const sectionTable = Buffer.alloc(sectionTableSize);
const sectionRead = await handle.read(
sectionTable,
0,
sectionTableSize,
sectionTableOffset,
);
throwIfTargetResolutionCancelled(signal);
if (sectionRead.bytesRead !== sectionTableSize) return undefined;
const debugFileOffset = peRvaToFileOffset(
debugDir.debugRva,
sectionTable,
numberOfSections,
debugDir.sizeOfHeaders,
Math.min(debugDir.debugSize, 4096),
);
if (debugFileOffset === undefined) return undefined;
const maxDebugSize = Math.min(debugDir.debugSize, 4096);
const debugDirectoryBuffer = Buffer.alloc(maxDebugSize);
const debugDirRead = await handle.read(
debugDirectoryBuffer,
0,
maxDebugSize,
debugFileOffset,
);
throwIfTargetResolutionCancelled(signal);
const numEntries = Math.floor(debugDirRead.bytesRead / 28);
for (let j = 0; j < numEntries; j++) {
const entryOffset = j * 28;
const type = debugDirectoryBuffer.readUInt32LE(entryOffset + 12);
if (type !== 2) continue; // IMAGE_DEBUG_TYPE_CODEVIEW
const sizeOfData = debugDirectoryBuffer.readUInt32LE(entryOffset + 16);
let pointerToRawData = debugDirectoryBuffer.readUInt32LE(entryOffset + 24);
if (pointerToRawData === 0) {
const addressOfRawData = debugDirectoryBuffer.readUInt32LE(
entryOffset + 20,
);
const mapped = peRvaToFileOffset(
addressOfRawData,
sectionTable,
numberOfSections,
debugDir.sizeOfHeaders,
Math.min(sizeOfData, 4096),
);
if (mapped === undefined) continue;
pointerToRawData = mapped;
}
if (sizeOfData < 16) continue;
const maxCodeViewRead = Math.min(sizeOfData, 4096);
const codeViewBuffer = Buffer.alloc(maxCodeViewRead);
const codeViewRead = await handle.read(
codeViewBuffer,
0,
maxCodeViewRead,
pointerToRawData,
);
throwIfTargetResolutionCancelled(signal);
const parsed = parseCodeViewData(
codeViewBuffer.subarray(0, codeViewRead.bytesRead),
sizeOfData,
);
if (parsed !== undefined) return parsed;
}
return undefined;
};
+1 -1
View File
@@ -158,7 +158,7 @@ const expandAddress = async (
state.residual.add(`Call relationships were unavailable for ${address}.`);
return ok(false);
}
const related = parseRelatedAddresses(result.value.result, relation);
const related = parseRelatedAddresses(result.value.result, relation, tool);
if (!related.ok) {
state.failures.push({
address,
+100
View File
@@ -498,6 +498,106 @@ it("reports host denial before target mismatch but keeps composed workflow prere
).toBe("target_required");
});
describe("binary_overview capability requirements", () => {
it("admits a provider with current_document and other mandatory capabilities", () => {
const capabilities = [
"list_segments",
"current_document",
"list_procedures",
"list_strings",
].map((operation) => ({ operation, available: true, reason: null }));
expect(
entry(
"binary_overview",
status({ open: true, kind: "executable", capabilities }),
),
).toMatchObject({
available: true,
reason: "available",
remediation: null,
});
});
it("admits a provider with list_documents and other mandatory capabilities", () => {
const capabilities = [
"list_segments",
"list_documents",
"list_procedures",
"list_strings",
].map((operation) => ({ operation, available: true, reason: null }));
expect(
entry(
"binary_overview",
status({ open: true, kind: "executable", capabilities }),
),
).toMatchObject({
available: true,
reason: "available",
remediation: null,
});
});
it("reports document selection remediation when neither current_document nor list_documents is declared", () => {
const capabilities = [
"list_segments",
"list_procedures",
"list_strings",
].map((operation) => ({ operation, available: true, reason: null }));
expect(
entry(
"binary_overview",
status({ open: true, kind: "executable", capabilities }),
),
).toMatchObject({
available: false,
reason: "provider_missing",
remediation:
"Configure a provider for one of: current_document, list_documents.",
});
});
it("reports missing segment enumeration independently when segments are missing", () => {
const capabilities = [
"current_document",
"list_procedures",
"list_strings",
].map((operation) => ({ operation, available: true, reason: null }));
expect(
entry(
"binary_overview",
status({ open: true, kind: "executable", capabilities }),
),
).toMatchObject({
available: false,
reason: "provider_missing",
remediation: "Configure a provider for required operation list_segments.",
});
});
it("reports provider_unavailable when declared document selection capability is unavailable", () => {
const capabilities = [
{ operation: "list_segments", available: true, reason: null },
{
operation: "current_document",
available: false,
reason: "Document view is closed",
},
{ operation: "list_procedures", available: true, reason: null },
{ operation: "list_strings", available: true, reason: null },
];
expect(
entry(
"binary_overview",
status({ open: true, kind: "executable", capabilities }),
),
).toMatchObject({
available: false,
reason: "provider_unavailable",
remediation: "Document view is closed",
});
});
});
describe("trace_feature requirements", () => {
const capabilities = (operations: readonly string[]) =>
operations.map((operation) => ({
+59 -22
View File
@@ -98,7 +98,9 @@ type AvailabilityContext = {
readonly policy: AvailabilityPolicy;
};
const ENHANCED_REQUIREMENTS: Readonly<Record<string, readonly string[]>> = {
const ENHANCED_REQUIREMENTS: Readonly<
Record<string, readonly (string | readonly string[])[]>
> = {
trace_native_values: ["analyze_function", "resolve_native_call_targets"],
trace_native_ui_action: [
"decode_interface_builder",
@@ -114,7 +116,7 @@ const ENHANCED_REQUIREMENTS: Readonly<Record<string, readonly string[]>> = {
find_xrefs_to_name: ["list_names", "xrefs"],
binary_overview: [
"list_segments",
"list_documents",
["current_document", "list_documents"],
"list_procedures",
"list_strings",
],
@@ -343,7 +345,7 @@ const workflowAvailabilityFor = ({
kind,
policy,
}: AvailabilityContext): Availability | null => {
if (name === "inspect_go_binary")
if (name === "inspect_go_binary" || name === "inspect_rust_binary")
return { reason: "available", remediation: null };
if (name === "inspect_sqlite_database") {
const capability = sqliteDatabaseCapability(process.versions.node);
@@ -642,27 +644,62 @@ const composedAvailability = (
};
const composedAvailabilityFor = (
requirements: readonly string[],
requirements: readonly (string | readonly string[])[],
descriptors: ReadonlyMap<string, ProviderDescriptor>,
): Availability => {
const missing = requirements.find((operation) => !descriptors.has(operation));
if (missing !== undefined)
return {
reason: "provider_missing",
remediation: `Configure a provider for required operation ${missing}.`,
};
const unavailable = requirements
.map((operation) => descriptors.get(operation))
.find((descriptor) => descriptor?.available === false);
if (unavailable !== undefined)
return {
reason:
unavailable.availability_code === "unsupported_host"
? "unsupported_host"
: "provider_unavailable",
remediation:
unavailable.reason ?? "Choose another target or configured provider.",
};
for (const requirement of requirements) {
if (typeof requirement === "string") {
if (!descriptors.has(requirement))
return {
reason: "provider_missing",
remediation: `Configure a provider for required operation ${requirement}.`,
};
} else {
const declared = requirement.some((operation) =>
descriptors.has(operation),
);
if (!declared)
return {
reason: "provider_missing",
remediation: `Configure a provider for one of: ${requirement.join(", ")}.`,
};
}
}
for (const requirement of requirements) {
if (typeof requirement === "string") {
const descriptor = descriptors.get(requirement);
if (descriptor?.available === false)
return {
reason:
descriptor.availability_code === "unsupported_host"
? "unsupported_host"
: "provider_unavailable",
remediation:
descriptor.reason ??
"Choose another target or configured provider.",
};
} else {
const anyAvailable = requirement.some(
(operation) => descriptors.get(operation)?.available === true,
);
if (!anyAvailable) {
const unavailable = requirement
.map((operation) => descriptors.get(operation))
.find((descriptor) => descriptor?.available === false);
if (unavailable !== undefined)
return {
reason:
unavailable.availability_code === "unsupported_host"
? "unsupported_host"
: "provider_unavailable",
remediation:
unavailable.reason ??
"Choose another target or configured provider.",
};
}
}
}
return { reason: "available", remediation: null };
};
@@ -49,7 +49,10 @@ export const inspectAnalysisViewValidated = (
): Result<Evidence, AnalysisError> => {
const accumulator =
input.view.kind === "api-surface"
? new WebNetworkApiSurfaceAccumulator()
? new WebNetworkApiSurfaceAccumulator(
undefined,
input.view.include_query_parameter_names === true,
)
: undefined;
if (input.source.kind === "inline" && accumulator !== undefined) {
const admitted = accumulator.admitInlineEvidence(input.source.evidence);
@@ -186,6 +186,28 @@ describe("analysis provider registry: binding failures and cancellation", () =>
expect(explicit.error.reason).toBe("target_unsupported");
});
it("rejects an unknown environment preference even when every candidate rejects the target", async () => {
const alpha = candidate("alpha");
const misconfigured = new AnalysisProviderRegistry(
[alpha.provider],
"missing",
);
for (const selected of [
await misconfigured.select(ARTIFACT_TARGET),
await misconfigured.select(ARTIFACT_TARGET, "missing"),
]) {
if (selected.ok) throw new Error("expected unknown provider rejection");
expect(projectAnalysisError(selected.error)).toMatchObject({
details: {
selection_reason: "unknown_provider",
requested_provider_id: "missing",
candidate_ids: ["alpha"],
},
});
}
});
it("does not bind a profile with unresolved version or adapter failure", async () => {
const unresolved = candidate("unresolved", { profile: "missing" });
const failed = candidate("failed", { profile: "error" });
@@ -176,7 +176,7 @@ export class AnalysisProviderRegistry {
return err(new AnalysisCancelledError("open_binary"));
if (
request === undefined &&
selector !== "auto" &&
this.#byId.has(selector) &&
baseline.length > 0 &&
baseline.every(
({ targetSupport }) => targetSupport.status === "unsupported",
+182 -103
View File
@@ -5,7 +5,10 @@ import {
analysisProfilesEqual,
type AnalysisProfileCommitment,
} from "../../domain/analysisProfile.js";
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
import {
AnalysisCancelledError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import { err, ok, type Result } from "../../domain/result.js";
import type { JsonValue } from "../../domain/jsonValue.js";
@@ -73,6 +76,7 @@ export class BinarySession
implements BinarySessionPort
{
#active: SessionBinding | undefined;
#externalMutationCleanupFailure: AnalysisError | undefined;
#pendingCleanup:
| {
readonly client: AnalysisClient;
@@ -158,6 +162,10 @@ export class BinarySession
);
}
invalidateSnapshotForExternalMutation(): void {
this.invalidateSnapshot();
}
/** Return the selected immutable profile, optionally scoped to an operation. */
analysisProfile(
operation?: AnalysisOperation,
@@ -245,110 +253,180 @@ export class BinarySession
resolve: () => Promise<Result<ResolvedSessionOpen, AnalysisError>>,
options: Pick<BinarySessionOpenOptions, "signal" | "snapshot">,
): Promise<Result<BinaryTarget, AnalysisError>> {
return this.#serialize(async (admittedThrough) => {
if (isAborted(options.signal))
return err(new AnalysisCancelledError("open_binary"));
const resolved = await resolve();
if (!resolved.ok) return resolved;
const { target, route, sameTarget } = resolved.value;
const { profile } = route;
if (isAborted(options.signal))
return err(new AnalysisCancelledError("open_binary"));
const activeProfile = this.#active?.profile;
const sameProfile =
activeProfile === null || activeProfile === undefined
? profile === null
: profile !== null && analysisProfilesEqual(activeProfile, profile);
await this.#drainCalls(admittedThrough);
if (isAborted(options.signal))
return err(new AnalysisCancelledError("open_binary"));
const pendingClosed = await this.#retryPendingCleanup();
if (!pendingClosed.ok) return pendingClosed;
if (isAborted(options.signal))
return err(new AnalysisCancelledError("open_binary"));
const retained = sameTarget && sameProfile ? this.#active : undefined;
if (retained !== undefined) {
const fastPath = await this.#tryRetainedFastPath(
retained,
target,
options,
);
if (fastPath !== undefined) return fastPath;
}
const previous = this.#active;
this.#active = undefined;
if (previous !== undefined) {
const closed = await this.#retireClient(
previous.client,
previous.route.identity.id,
);
if (!closed.ok) {
// A failed open retires the provider cache, not the investigation.
// Preserve Evidence and Unknown history for export and recovery.
this.clearSnapshot();
this.#clearRuntimeAvailability();
return closed;
}
}
if (isAborted(options.signal))
return err(
await this.#restoreAfterFailedOpen(
previous,
new AnalysisCancelledError("open_binary"),
),
);
const runId = randomUUID();
const client = route.createClient(target, { runId });
const started = await client.execute("health", {}, options);
if (!started.ok) {
return err(
await this.#failedOpen(
client,
route.identity.id,
previous,
started.error,
),
);
}
if (isAborted(options.signal)) {
return err(
await this.#failedOpen(
client,
route.identity.id,
previous,
new AnalysisCancelledError("open_binary"),
),
);
}
this.#active = {
return this.#serialize((admittedThrough) =>
this.#openWithinTransition(admittedThrough, resolve, options),
);
}
async #openWithinTransition(
admittedThrough: number,
resolve: () => Promise<Result<ResolvedSessionOpen, AnalysisError>>,
options: Pick<BinarySessionOpenOptions, "signal" | "snapshot">,
): Promise<Result<BinaryTarget, AnalysisError>> {
if (this.#externalMutationCleanupFailure?.cleanupIncomplete === true)
return err(this.#externalMutationCleanupFailure);
if (isAborted(options.signal))
return err(new AnalysisCancelledError("open_binary"));
const resolved = await resolve();
if (!resolved.ok) return resolved;
const { target, route, sameTarget } = resolved.value;
const { profile } = route;
if (isAborted(options.signal))
return err(new AnalysisCancelledError("open_binary"));
const activeProfile = this.#active?.profile;
const sameProfile =
activeProfile === null || activeProfile === undefined
? profile === null
: profile !== null && analysisProfilesEqual(activeProfile, profile);
await this.#drainCalls(admittedThrough);
if (isAborted(options.signal))
return err(new AnalysisCancelledError("open_binary"));
const pendingClosed = await this.#retryPendingCleanup();
if (!pendingClosed.ok) return pendingClosed;
if (isAborted(options.signal))
return err(new AnalysisCancelledError("open_binary"));
const retained = sameTarget && sameProfile ? this.#active : undefined;
if (retained !== undefined) {
const fastPath = await this.#tryRetainedFastPath(
retained,
target,
client,
profile,
route,
runId,
nativeSourceAdmitted: false,
};
this.#clearRuntimeAvailability();
this.resetSnapshotInvalidation();
if (options.snapshot === undefined) {
if (profile === null) this.clearSnapshot();
else this.selectSnapshot(target, profile);
options,
);
if (fastPath !== undefined) return fastPath;
}
const previous = this.#active;
this.#active = undefined;
if (previous !== undefined) {
const closed = await this.#retireClient(
previous.client,
previous.route.identity.id,
);
if (!closed.ok) {
// A failed open retires the provider cache, not the investigation.
// Preserve Evidence and Unknown history for export and recovery.
this.clearSnapshot();
this.#clearRuntimeAvailability();
return closed;
}
if (options.snapshot !== undefined) {
const imported = this.importAnalysisSnapshot(options.snapshot);
if (!imported.ok) {
this.#active = undefined;
return err(
await this.#failedOpen(
client,
route.identity.id,
previous,
imported.error,
),
);
}
}
if (isAborted(options.signal))
return err(
await this.#restoreAfterFailedOpen(
previous,
new AnalysisCancelledError("open_binary"),
),
);
const runId = randomUUID();
const client = route.createClient(target, { runId });
const started = await client.execute("health", {}, options);
if (!started.ok) {
return err(
await this.#failedOpen(
client,
route.identity.id,
previous,
started.error,
),
);
}
if (isAborted(options.signal)) {
return err(
await this.#failedOpen(
client,
route.identity.id,
previous,
new AnalysisCancelledError("open_binary"),
),
);
}
this.#active = {
target,
client,
profile,
route,
runId,
nativeSourceAdmitted: false,
};
this.#clearRuntimeAvailability();
this.resetSnapshotInvalidation();
if (options.snapshot === undefined) {
if (profile === null) this.clearSnapshot();
else this.selectSnapshot(target, profile);
}
if (options.snapshot !== undefined) {
const imported = this.importAnalysisSnapshot(options.snapshot);
if (!imported.ok) {
this.#active = undefined;
return err(
await this.#failedOpen(
client,
route.identity.id,
previous,
imported.error,
),
);
}
return ok(target);
}
return ok(target);
}
/** Serialize an external mutation and retire the potentially stale analysis. */
withAdmittedExternalMutation<Value>(
_path: string | undefined,
signal: AbortSignal | undefined,
operation: () => Promise<Result<Value, AnalysisError>>,
retirementFailure: (
value: Result<Value, AnalysisError>,
error: AnalysisError,
) => AnalysisError,
operationName = "execute_rizin_command",
cleanupRecovery?: (
failure: AnalysisError | undefined,
) => Promise<Result<null, AnalysisError>>,
): Promise<Result<Result<Value, AnalysisError>, AnalysisError>> {
return this.#serialize(async (admittedThrough) => {
if (isAborted(signal))
return err(new AnalysisCancelledError(operationName));
await this.#drainCalls(admittedThrough);
if (isAborted(signal))
return err(new AnalysisCancelledError(operationName));
if (this.#externalMutationCleanupFailure?.cleanupIncomplete === true) {
if (cleanupRecovery === undefined)
return err(this.#externalMutationCleanupFailure);
const recovered = await cleanupRecovery(
this.#externalMutationCleanupFailure,
);
if (!recovered.ok) return recovered;
if (this.#externalMutationCleanupFailure.cleanupIncomplete)
return err(this.#externalMutationCleanupFailure);
this.#externalMutationCleanupFailure = undefined;
}
const pendingCleanup = await this.#retryPendingCleanup();
if (!pendingCleanup.ok) return pendingCleanup;
const activeAtDispatch = this.#active;
if (activeAtDispatch?.route.binding?.identity.id === "ghidra")
return err(
new AnalysisOutputError(
operationName,
"Close the active Ghidra session explicitly before an external mutation; rebinding would discard its ephemeral analysis edits.",
),
);
// A protocol reply does not prove that background writers have stopped.
// Retire the old analysis and require an explicit fresh open rather than
// silently binding a snapshot while an unrestricted command can still write.
const retireTarget = activeAtDispatch !== undefined;
this.invalidateSnapshot();
const value = await operation();
this.#externalMutationCleanupFailure =
!value.ok && value.error.cleanupIncomplete ? value.error : undefined;
if (!retireTarget) return ok(value);
const retired = await this.#closeActive({}, false);
if (!retired.ok) return err(retirementFailure(value, retired.error));
return ok(value);
});
}
@@ -396,6 +474,7 @@ export class BinarySession
options: Pick<ExecutionOptions, "progress"> & {
readonly retainProviderDocuments?: boolean;
},
clearRecords = true,
): Promise<Result<null, AnalysisError>> {
const previous = this.#active;
this.#active = undefined;
@@ -417,7 +496,7 @@ export class BinarySession
: {}),
},
);
this.clearSessionRecords();
if (clearRecords) this.clearSessionRecords();
this.#clearRuntimeAvailability();
const fileResources = await this.closeWriteResources();
if (!closed.ok && !fileResources.ok)
@@ -48,6 +48,20 @@ export interface BinarySessionPort
signal: AbortSignal | undefined,
operation: (analysis: AnalysisOperationPort) => Promise<Value>,
): Promise<Result<Value, AnalysisError>>;
/** Serialize an external mutation and retire any active target afterward. */
withAdmittedExternalMutation<Value>(
_path: string | undefined,
signal: AbortSignal | undefined,
operation: () => Promise<Result<Value, AnalysisError>>,
retirementFailure: (
value: Result<Value, AnalysisError>,
error: AnalysisError,
) => AnalysisError,
operationName?: string,
cleanupRecovery?: (
failure: AnalysisError | undefined,
) => Promise<Result<null, AnalysisError>>,
): Promise<Result<Result<Value, AnalysisError>, AnalysisError>>;
open(
path: string,
options?: {
@@ -82,6 +96,8 @@ export interface BinarySessionPort
operation?: AnalysisOperation,
): AnalysisProfileCommitment | undefined;
allowsSnapshotReplay(operation: AnalysisOperation): boolean;
/** Invalidate cached Evidence before an external command may mutate the target. */
invalidateSnapshotForExternalMutation(): void;
recordWorkflowSnapshot(
input: WorkflowSnapshotRecordInput,
): Result<null, EvidenceIntegrityError>;
@@ -1023,6 +1023,28 @@ it("serializes script loading against concurrent close and unloads the loaded sc
expect(bindings.device.session.isDetached()).toBe(true);
});
it("drains startup when the provider loader initiates shutdown", async () => {
const bindings = new FakeDeviceManager();
let closing: Promise<void> | undefined;
const manager = new FridaInstrumentationManager({
deviceManagerLoader: async () => {
closing = manager.closeAll();
return bindings;
},
});
const started = await manager.startSession({
mode: "spawn",
deviceId: "local",
program: "/tmp/fixture",
});
if (!started.ok) throw started.error;
expect(closing).toBeDefined();
await closing;
expect(bindings.device.session.isDetached()).toBe(true);
expect(bindings.device.resumed).toEqual([512]);
expect(manager.status(started.value.sessionId)).toBeUndefined();
});
it("names the unknown session or script ID it rejects", async () => {
const { manager, started } = await startLocalAttachedSession();
if (!started.ok) throw started.error;
@@ -1,4 +1,8 @@
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type {
AnalysisError,
AnalysisErrorOptions,
} from "../../domain/analysisErrorBase.js";
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
import type { OptionalProviderLoadFailure } from "../OptionalObservationProviders.js";
import type { JsonValue } from "../../domain/jsonValue.js";
import type { Result } from "../../domain/result.js";
@@ -60,6 +64,15 @@ export interface FridaScriptObservation {
readonly messagesTruncated: boolean;
}
export class FridaScriptLoadCancelledError extends AnalysisCancelledError {
constructor(
readonly script: FridaScriptObservation,
options?: AnalysisErrorOptions,
) {
super("load_frida_script", options);
}
}
export interface FridaSessionStatus extends FridaSessionObservation {
/** True only after REA has successfully resumed this spawned target. */
readonly targetResumeObserved: boolean;
@@ -100,14 +113,20 @@ export interface FridaInstrumentationPort {
startSession(
input: StartFridaSessionInput,
): Promise<Result<FridaSessionObservation, AnalysisError>>;
/** Own cancellation and new-script cleanup before returning a final load outcome. */
loadScript(
sessionId: string,
source: FridaScriptSource,
signal?: AbortSignal,
): Promise<Result<FridaScriptObservation, AnalysisError>>;
resumeSession(sessionId: string): Promise<Result<null, AnalysisError>>;
resumeSession(
sessionId: string,
signal?: AbortSignal,
): Promise<Result<null, AnalysisError>>;
unloadScript(
sessionId: string,
scriptId: string,
signal?: AbortSignal,
): Promise<Result<null, AnalysisError>>;
status(sessionId: string): FridaSessionStatus | undefined;
closeSession(
@@ -3,6 +3,7 @@ import { join } from "node:path";
import { expect, it } from "vitest";
import { FridaScriptLoadCancelledError } from "./FridaInstrumentationPort.js";
import type { FridaInstrumentationPort } from "./FridaInstrumentationPort.js";
import { FridaInstrumentationService } from "./FridaInstrumentationService.js";
import {
@@ -569,3 +570,74 @@ it("cleans up a session and returns typed cancellation after a pending start", a
if (!result.ok) expect(result.error._tag).toBe("AnalysisCancelledError");
expect(closed).toEqual(["00000000-0000-4000-8000-000000000001"]);
});
it("retains a cancelled provider load's source and messages in one-shot Evidence", async () => {
const controller = new AbortController();
const script = {
...createScriptObservation(),
messages: [{ type: "send", payload: "cancelled-load" }],
};
const service = new FridaInstrumentationService(
createProvider({
async loadScript() {
controller.abort(new Error("cancel during native load"));
return {
ok: false,
error: new FridaScriptLoadCancelledError(script, {
cause: controller.signal.reason,
}),
};
},
}),
);
const result = await service.instrument(
{
mode: "spawn",
program: "/fixture",
source: { sourceKind: "inline", source: "send('cancelled-load')" },
durationMs: 0,
},
controller.signal,
);
if (result.ok) throw new Error("Cancelled instrumentation succeeded");
expect(result.error.partialObservation).toMatchObject({
normalized_result: {
source_kind: "inline",
source_sha256: script.sourceSha256,
messages: script.messages,
instrumentation_cleanup: "released",
},
});
});
it("preserves a provider-committed load when cancellation arrives during result delivery", async () => {
const controller = new AbortController();
let unloads = 0;
const script = createScriptObservation();
const service = new FridaInstrumentationService(
createProvider({
loadScript() {
const completed = Promise.resolve({ ok: true as const, value: script });
void completed.then(() =>
controller.abort(new Error("late cancellation")),
);
return completed;
},
async unloadScript() {
unloads += 1;
return { ok: true, value: null };
},
}),
);
const loaded = await service.loadScript(
createSession().sessionId,
{ sourceKind: "inline", source: "send('ready')" },
controller.signal,
);
expect(controller.signal.aborted).toBe(true);
if (!loaded.ok) throw loaded.error;
expect(loaded.value.normalized_result).toMatchObject({
script_id: script.scriptId,
});
expect(unloads).toBe(0);
});
@@ -12,6 +12,7 @@ import {
AnalysisInputError,
} from "../../domain/analysisErrorCore.js";
import { err, ok, type Result } from "../../domain/result.js";
import { FridaScriptLoadCancelledError } from "./FridaInstrumentationPort.js";
import type {
FridaDeviceSelector,
FridaInstrumentationPort,
@@ -181,8 +182,17 @@ export class FridaInstrumentationService {
async loadScript(
sessionId: string,
source: FridaScriptSource,
signal?: AbortSignal,
): Promise<Result<Evidence, AnalysisError>> {
const loaded = await this.#provider.loadScript(sessionId, source);
if (signal?.aborted)
return err(
new AnalysisCancelledError("load_frida_script", {
cause: signal.reason,
}),
);
const loaded = await this.#provider.loadScript(sessionId, source, signal);
if (!loaded.ok && loaded.error instanceof FridaScriptLoadCancelledError)
return err(cancelledScriptEvidence(sessionId, loaded.error));
return loaded.ok
? ok(
fridaEvidence("load_frida_script", scriptOutput(loaded.value), {
@@ -192,12 +202,12 @@ export class FridaInstrumentationService {
: loaded;
}
resumeSession(sessionId: string) {
return this.#provider.resumeSession(sessionId);
resumeSession(sessionId: string, signal?: AbortSignal) {
return this.#provider.resumeSession(sessionId, signal);
}
unloadScript(sessionId: string, scriptId: string) {
return this.#provider.unloadScript(sessionId, scriptId);
unloadScript(sessionId: string, scriptId: string, signal?: AbortSignal) {
return this.#provider.unloadScript(sessionId, scriptId, signal);
}
status(sessionId: string): FridaSessionStatus | undefined {
@@ -243,14 +253,19 @@ export class FridaInstrumentationService {
const loaded = await this.#provider.loadScript(
started.value.sessionId,
input.source,
signal,
);
let scriptObservation: FridaScriptObservation | undefined;
if (loaded.ok) scriptObservation = loaded.value;
else if (loaded.error instanceof FridaScriptLoadCancelledError)
scriptObservation = loaded.error.script;
if (signal?.aborted)
return this.#cancelSession(
"instrument_with_frida",
started.value,
input,
signal.reason,
loaded.ok ? loaded.value : undefined,
scriptObservation,
);
if (!loaded.ok) {
const closed = await this.#provider.closeSession(started.value.sessionId);
@@ -267,6 +282,7 @@ export class FridaInstrumentationService {
if (started.value.mode === "spawn") {
const resumed = await this.#provider.resumeSession(
started.value.sessionId,
signal,
);
if (signal?.aborted)
return this.#cancelSession(
@@ -462,3 +478,23 @@ const sessionStatusOutput = (status: FridaSessionStatus) => ({
messages: status.messages,
messages_truncated: status.messagesTruncated,
});
const cancelledScriptEvidence = (
sessionId: string,
error: FridaScriptLoadCancelledError,
): AnalysisCancelledError =>
new AnalysisCancelledError(error.operation, {
cause: error.cause,
cleanup: error.cleanup,
partialObservation: fridaEvidence(
error.operation,
{
...scriptOutput(error.script),
cleanup_error: error.cleanup?.reason ?? null,
script_cleanup: error.cleanupIncomplete
? "incomplete_or_unknown"
: "released",
},
{ session_id: sessionId },
),
});
@@ -92,7 +92,11 @@ export const compareManagedMemberPaths = async (
throw new EvidenceIntegrityError(
`Managed artifact digest changed after open: expected ${target.sha256}, observed ${snapshot.sha256} at ${target.path}`,
);
const inspection = inspectManagedMembersBytes(snapshot.bytes, target);
// Member comparison never reads literals, so it does not spend the
// decode budget on them.
const inspection = inspectManagedMembersBytes(snapshot.bytes, target, {
userStrings: false,
});
const evidence = createEvidence(target, MANAGED_STATIC_PROVIDER, {
operation: "inspect_managed_members",
parameters: {},
@@ -0,0 +1,19 @@
import type { EvidenceProvider } from "../../domain/evidence.js";
import type {
ObjdumpInput,
RizinInput,
} from "../../domain/reverseEngineering.js";
/** Provider-neutral command profile consumed by the shared application workflow. */
export interface ReverseEngineeringProviderCommand {
readonly executable: string;
readonly arguments: readonly string[];
readonly identity: EvidenceProvider;
readonly environmentOverrides?: Readonly<NodeJS.ProcessEnv>;
}
/** Provider-specific command construction stays outside the application layer. */
export interface ReverseEngineeringCommandPort {
objdump(input: ObjdumpInput): ReverseEngineeringProviderCommand;
rizin(input: RizinInput): ReverseEngineeringProviderCommand;
}
@@ -0,0 +1,948 @@
import { createHash, randomUUID } from "node:crypto";
import { createReadStream } from "node:fs";
import { stat as statPath } from "node:fs/promises";
import type { Stats } from "node:fs";
import { resolve } from "node:path";
import {
AnalysisAccessDeniedError,
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisInputError,
AnalysisResourceConstraintError,
AnalysisTimeoutError,
} from "../../domain/analysisErrorCore.js";
import type {
AnalysisCleanupObservation,
AnalysisError,
} from "../../domain/analysisErrorBase.js";
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import type { JsonValue } from "../../domain/jsonValue.js";
import { err, ok, type Result } from "../../domain/result.js";
import {
objdumpInputSchema,
rizinInputSchema,
} from "../../domain/reverseEngineering.js";
import type {
ReverseEngineeringCommandPort,
ReverseEngineeringProviderCommand,
} from "./ReverseEngineeringCommandPort.js";
import {
execFileOutput,
execFileOutputFailure,
} from "../../process/ExecFileOutput.js";
import {
OwnedCommandFailure,
runOwnedCommand,
} from "../../process/OwnedCommand.js";
import type { ProviderProcessSupervisor } from "../../process/ProviderProcess.js";
export type ReverseEngineeringOperation =
| "inspect_with_objdump"
| "execute_rizin_command";
const DEFAULT_TIMEOUT_MS = 120_000;
const MAX_COMBINED_OUTPUT_BYTES = 16 * 1024 * 1024;
// Eight concurrent captures bound retained provider output to 128 MiB.
const MAX_CONCURRENT_REVERSE_ENGINEERING_OPERATIONS = 8;
export interface ReverseEngineeringServiceOptions {
readonly environment?: Readonly<NodeJS.ProcessEnv>;
readonly commands: ReverseEngineeringCommandPort;
readonly run?: ReverseEngineeringCommandRunner;
readonly runOwned?: typeof runOwnedCommand;
readonly digest?: typeof digestFile;
readonly stat?: (path: string) => Promise<Stats>;
}
interface ReverseEngineeringCommandRunner {
(
command: string,
arguments_: readonly string[],
options?: Parameters<typeof execFileOutput>[2],
): Promise<{
readonly stdout: string;
readonly stderr: string;
readonly stdoutInvalidUtf8?: boolean;
readonly stderrInvalidUtf8?: boolean;
readonly stdoutBytes?: number;
readonly stderrBytes?: number;
}>;
}
export type ReverseEngineeringServiceRuntimeOptions = Omit<
ReverseEngineeringServiceOptions,
"commands" | "environment"
>;
/** Shared application workflow for caller-selected local analysis commands. */
export class ReverseEngineeringService {
readonly #environment: Readonly<NodeJS.ProcessEnv>;
readonly #commands: ReverseEngineeringCommandPort;
readonly #run: ReverseEngineeringCommandRunner;
readonly #digest: typeof digestFile;
readonly #stat: (path: string) => Promise<Stats>;
readonly #pendingCleanup = new Map<
ProviderProcessSupervisor,
{
readonly observation: AnalysisCleanupObservation;
readonly failures: Set<AnalysisError>;
readonly retryFailure?: AnalysisError;
}
>();
readonly #activeOperations = new Map<
AbortController,
Promise<Result<Evidence, AnalysisError>>
>();
#closing = false;
#closePromise: Promise<void> | undefined;
constructor(options: ReverseEngineeringServiceOptions) {
this.#environment = { ...(options.environment ?? process.env) };
this.#commands = options.commands;
this.#run =
options.run ??
runOwnedCommandOutput(
options.runOwned ?? runOwnedCommand,
(owner, cleanup) =>
this.#pendingCleanup.set(owner, {
observation: cleanup,
failures: this.#pendingCleanup.get(owner)?.failures ?? new Set(),
}),
);
this.#digest = options.digest ?? digestFile;
this.#stat = options.stat ?? statPath;
}
/** Ask retained process owners to settle cleanup before admitting more work. */
async retryCleanup(
operation = "reverse_engineering_cleanup",
): Promise<Result<null, AnalysisError>> {
let failure: AnalysisError | undefined;
for (const [owner, retained] of this.#pendingCleanup) {
let stopped: Awaited<ReturnType<ProviderProcessSupervisor["stop"]>>;
try {
stopped = await owner.stop();
} catch (cause) {
stopped = {
status: "incomplete",
reason: cause instanceof Error ? cause.message : String(cause),
};
}
if (stopped.status === "incomplete") {
const observation = {
reason: stopped.reason,
resources: retained.observation.resources,
};
let retryFailure = retained.retryFailure;
if (retryFailure === undefined) {
retryFailure = new AnalysisOutputError(
operation,
"A previous provider process still requires cleanup.",
{ cleanup: observation },
);
retained.failures.add(retryFailure);
}
this.#pendingCleanup.set(owner, {
observation,
failures: retained.failures,
retryFailure,
});
if (failure === undefined) failure = retryFailure;
} else {
for (const previous of retained.failures) previous.resolveCleanup();
this.#pendingCleanup.delete(owner);
}
}
return failure === undefined ? ok(null) : err(failure);
}
/** Retry cleanup for provider process groups retained after an incomplete stop. */
close(): Promise<void> {
this.#closing = true;
this.#closePromise ??= this.#closeActiveOperationsAndCleanup().catch(
(cause: unknown) => {
this.#closePromise = undefined;
throw cause;
},
);
return this.#closePromise;
}
async #closeActiveOperationsAndCleanup(): Promise<void> {
const active = [...this.#activeOperations.entries()];
for (const [controller] of active) controller.abort();
await Promise.allSettled(active.map(([, operation]) => operation));
const cleanup = await this.retryCleanup();
if (!cleanup.ok) throw cleanup.error;
}
inspectWithObjdump(
rawInput: unknown,
options: { readonly signal?: AbortSignal } = {},
): Promise<Result<Evidence, AnalysisError>> {
const parsed = objdumpInputSchema.safeParse(rawInput);
if (!parsed.success)
return Promise.resolve(
err(new AnalysisInputError("inspect_with_objdump")),
);
const input = parsed.data;
const command = this.#commands.objdump(input);
return this.#observe(
"inspect_with_objdump",
command,
input.operation === "architectures" ? undefined : input.path,
input,
options.signal,
);
}
executeRizinCommand(
rawInput: unknown,
options: { readonly signal?: AbortSignal } = {},
): Promise<Result<Evidence, AnalysisError>> {
const parsed = rizinInputSchema.safeParse(rawInput);
if (!parsed.success)
return Promise.resolve(
err(new AnalysisInputError("execute_rizin_command")),
);
const input = parsed.data;
const command = this.#commands.rizin(input);
return this.#observe(
"execute_rizin_command",
command,
input.path,
input,
options.signal,
);
}
#observe(
operation: ReverseEngineeringOperation,
profile: ReverseEngineeringProviderCommand,
path: string | undefined,
parameters: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
): Promise<Result<Evidence, AnalysisError>> {
if (signal?.aborted)
return Promise.resolve(err(new AnalysisCancelledError(operation)));
if (this.#closing)
return Promise.resolve(
err(
new AnalysisOutputError(
operation,
"Reverse-engineering service is closed.",
),
),
);
if (
this.#activeOperations.size >=
MAX_CONCURRENT_REVERSE_ENGINEERING_OPERATIONS
)
return Promise.resolve(
err(
new AnalysisResourceConstraintError(
operation,
"transport",
"Concurrent reverse-engineering operation capacity reached.",
{
max_concurrent_operations:
MAX_CONCURRENT_REVERSE_ENGINEERING_OPERATIONS,
active_operations: this.#activeOperations.size,
},
),
),
);
const controller = new AbortController();
const relayAbort = (): void => controller.abort(signal?.reason);
if (signal instanceof AbortSignal) {
if (signal.aborted) relayAbort();
else signal.addEventListener("abort", relayAbort, { once: true });
}
const operationSignal =
signal === undefined || signal instanceof AbortSignal
? controller.signal
: signal;
const running = this.#observeProvider(
operation,
profile,
path,
parameters,
operationSignal,
);
const tracked = running.finally(() => {
signal?.removeEventListener("abort", relayAbort);
this.#activeOperations.delete(controller);
});
this.#activeOperations.set(controller, tracked);
return tracked;
}
async #observeProvider(
operation: ReverseEngineeringOperation,
profile: ReverseEngineeringProviderCommand,
path: string | undefined,
parameters: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
): Promise<Result<Evidence, AnalysisError>> {
const { executable: command, arguments: args } = profile;
if (signal?.aborted) return err(new AnalysisCancelledError(operation));
const cleanup = await this.retryCleanup(operation);
if (!cleanup.ok) return cleanup;
const absolutePath = path === undefined ? undefined : resolve(path);
let digest: string | undefined;
try {
if (absolutePath !== undefined)
digest = await this.#digest(absolutePath, signal, this.#stat);
} catch (cause) {
const code = (cause as NodeJS.ErrnoException).code;
if (signal?.aborted)
return err(new AnalysisCancelledError(operation, { cause }));
if (code === "EACCES" || code === "EPERM") {
const deniedPath = absolutePath === undefined ? command : absolutePath;
return err(
new AnalysisAccessDeniedError(operation, deniedPath, code, {
cause,
}),
);
}
if (code === "ETIMEDOUT")
return err(
new AnalysisTimeoutError(operation, DEFAULT_TIMEOUT_MS, { cause }),
);
return err(new AnalysisInputError(operation, { cause }));
}
let stdout = "";
let stderr = "";
let stdoutBytes = 0;
let stderrBytes = 0;
let exitCode: number | string | null = 0;
let signalName: string | null = null;
let outputTruncated = false;
let stdoutInvalidUtf8 = false;
let stderrInvalidUtf8 = false;
let cleanupIncomplete = false;
let cleanupOnlyFailure = false;
let completionStatus: "complete" | "unknown" = "complete";
let failure: AnalysisError | undefined;
let cleanupOwner: ProviderProcessSupervisor | undefined;
let earlyFailure: AnalysisError | undefined;
try {
const output = await this.#run(command, args, {
env: {
...this.#environment,
...profile.environmentOverrides,
},
signal,
timeout: DEFAULT_TIMEOUT_MS,
stopSignal: "SIGTERM",
maxBuffer: MAX_COMBINED_OUTPUT_BYTES,
});
stdout = output.stdout;
stderr = output.stderr;
stdoutBytes = output.stdoutBytes ?? Buffer.byteLength(stdout);
stderrBytes = output.stderrBytes ?? Buffer.byteLength(stderr);
stdoutInvalidUtf8 = output.stdoutInvalidUtf8 === true;
stderrInvalidUtf8 = output.stderrInvalidUtf8 === true;
} catch (cause) {
cleanupOwner =
cause instanceof OwnedOutputFailure ? cause.cleanupOwner : undefined;
if (
cause instanceof OwnedOutputFailure &&
cause.capabilityError !== undefined
)
earlyFailure = new AnalysisCapabilityUnavailableError(
cause.capabilityError.providerId,
cause.capabilityError.operation,
cause.capabilityError.reason,
{
cause: cause.capabilityError,
...(cause.capabilityError.diagnostics === undefined
? {}
: { diagnostics: cause.capabilityError.diagnostics }),
...(cause.capabilityError.capturedOutput === undefined
? {}
: { capturedOutput: cause.capabilityError.capturedOutput }),
...(cause.capabilityError.partialObservation === undefined
? {}
: {
partialObservation: cause.capabilityError.partialObservation,
}),
...(cause.capabilityError.userMessage === undefined
? {}
: { userMessage: cause.capabilityError.userMessage }),
retryable: cause.capabilityError.retryable,
...ownedCleanupOptions(cause),
},
);
const capture = execFileOutputFailure(cause);
const code =
capture?.code ?? (cause as NodeJS.ErrnoException).code ?? undefined;
if (earlyFailure === undefined && code === "E2BIG")
earlyFailure = new AnalysisResourceConstraintError(
operation,
"transport",
"The host rejected the provider command because its argument list exceeds the process launch limit.",
{
argument_bytes: args.reduce(
(bytes, argument, index) =>
bytes + Buffer.byteLength(argument) + (index === 0 ? 0 : 1),
0,
),
},
{ cause, ...ownedCleanupOptions(cause) },
);
if (
earlyFailure === undefined &&
(capture === undefined ||
code === "ENOENT" ||
code === "ERR_PROVIDER_LAUNCH")
) {
if (signal?.aborted || code === "ABORT_ERR")
earlyFailure = new AnalysisCancelledError(operation, {
cause,
...ownedCleanupOptions(cause),
});
else if (code === "ETIMEDOUT")
earlyFailure = new AnalysisTimeoutError(
operation,
DEFAULT_TIMEOUT_MS,
{
cause,
...ownedCleanupOptions(cause),
},
);
else if (code === "EACCES" || code === "EPERM")
earlyFailure = new AnalysisAccessDeniedError(
operation,
command,
code,
{
cause,
...ownedCleanupOptions(cause),
},
);
else
earlyFailure = new AnalysisCapabilityUnavailableError(
operation === "inspect_with_objdump" ? "objdump" : "rizin",
operation,
`Unable to run configured command (${String(code ?? "unknown error")})`,
{ cause, ...ownedCleanupOptions(cause) },
);
}
if (earlyFailure === undefined && capture !== undefined) {
stdout = capture.stdout;
stderr = capture.stderr;
stdoutBytes = capture.stdoutBytes ?? Buffer.byteLength(stdout);
stderrBytes = capture.stderrBytes ?? Buffer.byteLength(stderr);
exitCode = capture.code;
signalName = capture.signal;
outputTruncated = capture.outputTruncated;
if (capture.collectionFailure) {
exitCode = null;
completionStatus = "unknown";
}
const capturedOutput = {
stdout,
stderr,
truncated: outputTruncated,
stdout_bytes: stdoutBytes,
stderr_bytes: stderrBytes,
exit_code:
!capture.collectionFailure && typeof capture.code === "number"
? capture.code
: null,
signal: capture.signal,
};
if (signal?.aborted || code === "ABORT_ERR")
failure = new AnalysisCancelledError(operation, {
cause,
capturedOutput,
...ownedCleanupOptions(cause),
});
else if (code === "ETIMEDOUT")
failure = new AnalysisTimeoutError(operation, DEFAULT_TIMEOUT_MS, {
cause,
capturedOutput,
...ownedCleanupOptions(cause),
});
else if (code === "EACCES" || code === "EPERM")
failure = new AnalysisAccessDeniedError(operation, command, code, {
cause,
capturedOutput,
...ownedCleanupOptions(cause),
});
if (
cause instanceof OwnedOutputFailure &&
cause.cleanup !== undefined
) {
cleanupIncomplete = true;
if (failure === undefined) {
cleanupOnlyFailure =
!capture.collectionFailure &&
!capture.outputTruncated &&
!capture.killed &&
capture.signal === null &&
typeof capture.code === "number" &&
!signal?.aborted;
failure = new AnalysisOutputError(
operation,
"Provider process cleanup remains incomplete.",
{
cause,
capturedOutput,
cleanup: cause.cleanup,
cleanupOnly: cleanupOnlyFailure,
},
);
}
}
if (
failure === undefined &&
cause instanceof OwnedOutputFailure &&
cause.collectionFailure
)
failure = new AnalysisOutputError(
operation,
"Provider output collection failed.",
{ cause, capturedOutput },
);
if (
capture.killed ||
capture.signal !== null ||
typeof capture.code !== "number"
) {
exitCode = null;
completionStatus = "unknown";
}
if (cause instanceof OwnedOutputFailure) {
stdoutInvalidUtf8 = cause.stdoutInvalidUtf8;
stderrInvalidUtf8 = cause.stderrInvalidUtf8;
}
}
}
if (earlyFailure !== undefined)
return err(this.#registerCleanupFailure(earlyFailure, cleanupOwner));
if (failure !== undefined && cleanupOwner !== undefined)
failure = this.#registerCleanupFailure(failure, cleanupOwner);
let digestAfter: string | null = null;
if (absolutePath === undefined) {
digestAfter = null;
} else if (cleanupIncomplete) {
if (!cleanupOnlyFailure) completionStatus = "unknown";
} else {
try {
digestAfter = await this.#digest(absolutePath, signal, this.#stat);
} catch {
// Preserve the provider's collected observations if the artifact vanished or became unreadable.
}
}
if (signal?.aborted && failure === undefined) {
failure = new AnalysisCancelledError(operation, {
capturedOutput: {
stdout,
stderr,
truncated: outputTruncated,
stdout_bytes: stdoutBytes,
stderr_bytes: stderrBytes,
exit_code: typeof exitCode === "number" ? exitCode : null,
signal: signalName,
},
});
exitCode = null;
completionStatus = "unknown";
}
const artifactChanged =
absolutePath === undefined
? null
: digestAfter === null || digest === undefined
? null
: digestAfter !== digest;
const result = {
stdout,
stderr,
exit_code: exitCode,
signal: signalName,
output_truncated: outputTruncated,
completion_status: completionStatus,
artifact_sha256_after: absolutePath === undefined ? null : digestAfter,
artifact_changed: absolutePath === undefined ? null : artifactChanged,
};
const limitations = [
...(absolutePath === undefined
? [
"The objdump version is not reported; the output lists BFD targets advertised by the installed tool and does not establish support for the selected artifact.",
]
: [
"The executable version and supported formats are reported as unknown because no reliable version probe was performed.",
]),
"A non-zero process exit is preserved as an observed command result.",
...(operation === "inspect_with_objdump" &&
parameters.follow_debug_links === true
? [
"DWARF output may include local debug-link files whose identities are not bound to Evidence.",
]
: []),
...(operation === "execute_rizin_command"
? [
"Rizin commands and retained plugins may read files or access network resources outside the selected artifact; those external inputs are not bound to Evidence.",
]
: []),
...(stdoutInvalidUtf8 || stderrInvalidUtf8
? [
`Captured ${[
...(stdoutInvalidUtf8 ? ["stdout"] : []),
...(stderrInvalidUtf8 ? ["stderr"] : []),
].join(
" and ",
)} bytes contain invalid or incomplete UTF-8; replacement characters in the text capture do not preserve the original bytes.`,
]
: []),
...(outputTruncated
? [
"The provider command ended before completion could be confirmed; captured output is partial.",
]
: []),
...(signalName === null
? []
: [
`The provider process terminated by signal ${signalName}; captured output may be partial and command completion is unknown.`,
]),
...(failure === undefined ||
(failure instanceof AnalysisOutputError && failure.cleanupOnly)
? []
: [
`Command completion is unknown because the operation failed with ${failure._tag}: ${failure.message}`,
]),
...(absolutePath === undefined
? [
"This output lists BFD targets advertised by the installed objdump and is independent of the selected artifact.",
]
: [
"When both are available, pre-run and post-run digests detect artifact changes across the provider call but cannot prove the exact bytes consumed during the call.",
]),
...(artifactChanged === true
? [
"The provider command may have changed the artifact while analysis was running; pre-run and post-run digests are both reported.",
]
: []),
...(absolutePath !== undefined && digestAfter === null
? [
cleanupIncomplete
? "The post-run artifact digest was not captured because owned provider cleanup was incomplete at observation time; artifact changes during the command remain unquantified."
: signal?.aborted
? "The post-run artifact digest is unknown because cancellation interrupted the digest."
: "The post-run artifact digest is unknown because the artifact could not be read after the provider call.",
]
: []),
];
const evidence = createEvidence(
absolutePath === undefined || digest === undefined
? undefined
: { path: absolutePath, sha256: digest, format: "unknown" },
profile.identity,
{
predicateType: "rea.reverse-engineering.command-observation",
operation,
parameters: {
...(absolutePath === undefined
? { operation: "architectures" }
: parameters),
provider_executable: command,
command_arguments: [...args],
},
rawResult: result,
result,
limitations,
...(absolutePath === undefined
? {}
: {
locations: [
{ kind: "artifact-path" as const, path: absolutePath },
],
}),
},
);
return failure === undefined
? ok(evidence)
: err(failure.retainPartialObservation(evidence));
}
#registerCleanupFailure(
failure: AnalysisError,
cleanupOwner: ProviderProcessSupervisor | undefined,
): AnalysisError {
if (cleanupOwner !== undefined && failure.cleanupIncomplete)
this.#pendingCleanup.get(cleanupOwner)?.failures.add(failure);
return failure;
}
}
interface OwnedOutputFailureOptions {
readonly stdout: string;
readonly stderr: string;
readonly code: number | string | null;
readonly signal: string | null;
readonly outputTruncated: boolean;
readonly stdoutInvalidUtf8: boolean;
readonly stderrInvalidUtf8: boolean;
readonly stdoutBytes: number;
readonly stderrBytes: number;
readonly capabilityError?: AnalysisCapabilityUnavailableError;
readonly collectionFailure?: boolean;
readonly cleanup?: AnalysisCleanupObservation;
readonly cleanupOwner?: ProviderProcessSupervisor;
readonly cause?: unknown;
}
class OwnedOutputFailure extends Error {
readonly stdout: string;
readonly stderr: string;
readonly code: number | string | null;
readonly signal: string | null;
readonly outputTruncated: boolean;
readonly stdoutInvalidUtf8: boolean;
readonly stderrInvalidUtf8: boolean;
readonly stdoutBytes: number;
readonly stderrBytes: number;
readonly capabilityError: AnalysisCapabilityUnavailableError | undefined;
readonly collectionFailure: boolean;
readonly cleanup: AnalysisCleanupObservation | undefined;
readonly cleanupOwner: ProviderProcessSupervisor | undefined;
constructor(options: OwnedOutputFailureOptions) {
super("Owned provider command did not produce a complete result.", {
cause: options.cause,
});
this.stdout = options.stdout;
this.stderr = options.stderr;
this.code = options.code;
this.signal = options.signal;
this.outputTruncated = options.outputTruncated;
this.stdoutInvalidUtf8 = options.stdoutInvalidUtf8;
this.stderrInvalidUtf8 = options.stderrInvalidUtf8;
this.stdoutBytes = options.stdoutBytes;
this.stderrBytes = options.stderrBytes;
this.capabilityError = options.capabilityError;
this.collectionFailure = options.collectionFailure ?? false;
this.cleanup = options.cleanup;
this.cleanupOwner = options.cleanupOwner;
}
}
const runOwnedCommandOutput =
(
runOwned: typeof runOwnedCommand,
onCleanupOwner: (
owner: ProviderProcessSupervisor,
cleanup: AnalysisCleanupObservation,
) => void,
): ReverseEngineeringCommandRunner =>
async (command, args, options = {}) => {
const spawnEnv = { ...options.env };
try {
const snapshot = await runOwned(
{
command,
arguments: [...args],
runId: randomUUID(),
expectedCommand: null,
env: spawnEnv,
hostEnvironment: {},
sweepTokenOwnedProcesses: true,
},
{
timeoutMs: DEFAULT_TIMEOUT_MS,
diagnosticBytes: MAX_COMBINED_OUTPUT_BYTES,
acceptNonZeroExit: true,
},
{ signal: options.signal },
);
if (snapshot.signal !== null && snapshot.signal !== undefined)
throw new OwnedOutputFailure({
stdout: snapshot.stdout.text,
stderr: snapshot.stderr.text,
code: snapshot.exitCode ?? null,
signal: snapshot.signal,
outputTruncated: snapshot.diagnosticTruncated === true,
stdoutInvalidUtf8: snapshot.stdout.invalidUtf8 === true,
stderrInvalidUtf8: snapshot.stderr.invalidUtf8 === true,
stdoutBytes: snapshot.stdout.bytes,
stderrBytes: snapshot.stderr.bytes,
});
if (snapshot.exitCode !== 0)
throw new OwnedOutputFailure({
stdout: snapshot.stdout.text,
stderr: snapshot.stderr.text,
code: snapshot.exitCode ?? null,
signal: null,
outputTruncated: snapshot.diagnosticTruncated === true,
stdoutInvalidUtf8: snapshot.stdout.invalidUtf8 === true,
stderrInvalidUtf8: snapshot.stderr.invalidUtf8 === true,
stdoutBytes: snapshot.stdout.bytes,
stderrBytes: snapshot.stderr.bytes,
});
return {
stdout: snapshot.stdout.text,
stderr: snapshot.stderr.text,
stdoutInvalidUtf8: snapshot.stdout.invalidUtf8 === true,
stderrInvalidUtf8: snapshot.stderr.invalidUtf8 === true,
stdoutBytes: snapshot.stdout.bytes,
stderrBytes: snapshot.stderr.bytes,
};
} catch (cause) {
if (!(cause instanceof OwnedCommandFailure)) throw cause;
if (cause.cleanupOwner !== undefined && cause.cleanupFailure !== null)
onCleanupOwner(cause.cleanupOwner, {
reason: cause.cleanupFailure,
resources: cause.resources,
});
const snapshot = cause.snapshot;
const launchErrorCode =
cause.cause instanceof Error
? Reflect.get(cause.cause, "code")
: undefined;
const code =
cause.reason === "cancelled"
? "ABORT_ERR"
: cause.reason === "timeout"
? "ETIMEDOUT"
: cause.reason === "output-limit"
? "ERR_CHILD_PROCESS_STDIO_MAXBUFFER"
: launchErrorCode === "E2BIG"
? "E2BIG"
: snapshot === null
? "ERR_PROVIDER_LAUNCH"
: (snapshot.exitCode ?? null);
throw new OwnedOutputFailure({
stdout: snapshot?.stdout.text ?? "",
stderr: snapshot?.stderr.text ?? "",
code,
signal: snapshot?.signal ?? null,
outputTruncated: snapshot?.diagnosticTruncated === true,
stdoutInvalidUtf8: snapshot?.stdout.invalidUtf8 === true,
stderrInvalidUtf8: snapshot?.stderr.invalidUtf8 === true,
stdoutBytes: snapshot?.stdout.bytes ?? 0,
stderrBytes: snapshot?.stderr.bytes ?? 0,
...(cause.cause instanceof AnalysisCapabilityUnavailableError
? { capabilityError: cause.cause }
: {}),
...(cause.collectionFailure ? { collectionFailure: true } : {}),
...(cause.cleanupFailure === null
? {}
: {
cleanup: {
reason: cause.cleanupFailure,
resources: cause.resources,
},
}),
...(cause.cleanupOwner === undefined
? {}
: { cleanupOwner: cause.cleanupOwner }),
cause,
});
}
};
const ownedCleanupOptions = (
cause: unknown,
): { readonly cleanup?: AnalysisCleanupObservation } =>
cause instanceof OwnedOutputFailure && cause.cleanup !== undefined
? { cleanup: cause.cleanup }
: {};
const digestFile = async (
path: string,
signal?: AbortSignal,
stat: (path: string) => Promise<Stats> = statPath,
): Promise<string> => {
const info = await statWithDeadline(path, signal, stat);
if (!info.isFile())
throw Object.assign(new Error("Artifact digest requires a regular file"), {
code: "EINVAL",
});
return new Promise<string>((resolveDigest, rejectDigest) => {
const hash = createHash("sha256");
const stream = createReadStream(path);
const timer = setTimeout(
() =>
stream.destroy(
Object.assign(new Error("Artifact digest timed out"), {
code: "ETIMEDOUT",
}),
),
DEFAULT_TIMEOUT_MS,
);
const abort = (): void => {
stream.destroy(new AnalysisCancelledError("artifact_digest"));
};
const cleanup = (): void => {
clearTimeout(timer);
signal?.removeEventListener("abort", abort);
};
if (signal?.aborted) {
cleanup();
stream.destroy();
rejectDigest(new AnalysisCancelledError("artifact_digest"));
return;
}
signal?.addEventListener("abort", abort, { once: true });
stream.on("data", (chunk: Buffer | string) => hash.update(chunk));
stream.once("error", (cause: Error) => {
cleanup();
rejectDigest(cause);
});
stream.once("end", () => {
cleanup();
resolveDigest(hash.digest("hex"));
});
});
};
const statWithDeadline = (
path: string,
signal: AbortSignal | undefined,
stat: (path: string) => Promise<Stats>,
): Promise<Stats> => {
if (signal?.aborted)
return Promise.reject(new AnalysisCancelledError("artifact_digest"));
return new Promise<Stats>((resolveStat, rejectStat) => {
let settled = false;
const finish = (cause?: unknown, value?: Stats): void => {
if (settled) return;
settled = true;
clearTimeout(timer);
signal?.removeEventListener("abort", abort);
if (cause !== undefined) rejectStat(cause);
else resolveStat(value!);
};
const abort = (): void =>
finish(new AnalysisCancelledError("artifact_digest"));
const timer = setTimeout(
() =>
finish(
Object.assign(new Error("Artifact stat timed out"), {
code: "ETIMEDOUT",
}),
),
DEFAULT_TIMEOUT_MS,
);
signal?.addEventListener("abort", abort, { once: true });
if (signal?.aborted) {
abort();
return;
}
// Promise handlers stay attached after timeout/cancellation so a delayed
// stat rejection is observed and cannot become an unhandled rejection.
try {
void stat(path).then(
(info) => finish(undefined, info),
(cause: unknown) => finish(cause),
);
} catch (cause) {
finish(cause);
}
});
};
+19
View File
@@ -0,0 +1,19 @@
import type {
ExecutionOptions,
ProviderIdentity,
} from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type {
InspectRustBinaryInput,
RustBinary,
} from "../../domain/rust/rustBinary.js";
import type { Result } from "../../domain/result.js";
/** Replaceable offline dependency reader with no target-execution authority. */
export interface RustBinaryPort {
readonly identity: ProviderIdentity;
inspect(
input: InspectRustBinaryInput,
options?: ExecutionOptions,
): Promise<Result<RustBinary, AnalysisError>>;
}

Some files were not shown because too many files have changed in this diff Show More