Compare commits

...
Author SHA1 Message Date
N0zoM1z0 c2f5fc6612 docs(hopper): clarify realpath fallback scope 2026-10-06 19:00:55 +08:00
Vinay PrasadandGitHub 6847bc9473 docs(hopper): document HopperTargetLease realpath fallback
Closes #642
2026-10-06 15:08:54 +05:30
N0zoM1z0andGitHub 9bab55337a feat(ghidra): add atomic function annotation edits (#709)
* feat(ghidra): edit function annotations atomically

Return annotation readback and refreshed function analysis through CLI and MCP. Own each database transaction, invalidate caches and immutable snapshots, preserve executable bytes, and retain the Windows mutation boundary.

Assisted-by: Nitori (gensokyo-skills:nitori-reverse-engineering)

* fix(ghidra): preserve qualified function annotation identity

Preserve namespaces during local name writes and match qualified readback to the refreshed dossier. Add a producer-shaped regression and verify a real namespaced C++ function through the CLI.

Assisted-by: Nitori (gensokyo-skills:nitori-reverse-engineering)

* test(ghidra): align verification with annotation authority

Keep strict capability and profile checks while admitting the explicit session metadata operation. Verify packaged transport authority and atomic transaction commitments and preserve a read-only Windows expectation.

Assisted-by: Nitori (gensokyo-skills:nitori-reverse-engineering)
2026-10-06 17:24:33 +08:00
Kaoru0822andGitHub c3bc38bf6c Merge pull request #708 from kaoru0822-kitauji/fix/function-verification-source-parameters
fix(reconstruction): accept function comparison source parameters
2026-10-06 02:18:20 -07:00
Kaoru0822 7a96391001 fix(reconstruction): accept function comparison source parameters 2026-10-06 02:11:10 -07:00
Kaoru0822andGitHub ab5a1c61b1 Merge pull request #706 from kaoru0822-kitauji/fix/process-evidence-provider-identity
fix(evidence): admit current process provider identity
2026-10-06 02:00:47 -07:00
Kaoru0822andGitHub f04445c57c Merge pull request #704 from kaoru0822-kitauji/fix/arm64e-native-inspection
fix(native): select concrete arm64e Mach-O slices
2026-10-06 02:00:35 -07:00
Kaoru0822andGitHub 44b3627ab0 Merge pull request #703 from kaoru0822-kitauji/fix/process-pid-normalization
fix(process): honor disabled PID normalization in samples
2026-10-06 02:00:19 -07:00
N0zoM1z0andGitHub 26881da76a feat(ghidra): enable Windows x64 read-only analysis (#699)
* feat(ghidra): enable Windows x64 read-only analysis

* test(ghidra): exercise native Windows runtime boundaries

* test(ghidra): verify current Windows inventory and isolate ACL observer

* fix(ghidra): align Windows admission and address P0 review
2026-10-06 16:53:33 +08:00
Kaoru0822 d311940f24 fix(evidence): admit current process provider identity 2026-10-06 01:43:45 -07:00
cf061159ab fix: integrate 14 approved fix PRs (668,671,673,675,678-681,685-690) (#705)
* fix(javascript): preserve array index positions

Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>

* fix(javascript): respect object property overwrite order

Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>

* test(javascript): cover uncertain spread discriminants

Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>

* fix(javascript): keep nonfinite values outside JSON lattice

Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>

* fix(dotnet): keep non-CIL method implementations unknown

Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>

* test(package): separate CIL reconstruction from native imports

Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>

* fix(javascript): invalidate values on nontrivial binding writes

Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>

* fix(artifacts): align native DMG mount and detach lifecycle

Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>

* fix(browser): retain all literal worker import arguments

Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>

* fix(native): preserve final demangled symbol whitespace

Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>

* fix(dotnet): preserve C identifier underscores in native matching

Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>

* fix(browser): respect metadata key and overwrite semantics

Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>

* fix(javascript): keep optional parameter input unknown

Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>

* fix(dotnet): report observed method metadata changes

Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>

* docs(dotnet): synchronize generated conformance skill digest

Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>

* fix(browser): reject malformed indexed source-map offsets

Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>

* fix(native): preserve numeric-looking Mach-O identifiers

Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>

* docs: regenerate catalogs for integrated fix batch

* docs: regenerate catalogs after merging main (#702)

---------

Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>
Co-authored-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>
2026-10-06 16:31:00 +08:00
N0zoM1z0andGitHub 5bcb6645b5 feat(ghidra): admit explicit DOS COM analysis (#702)
* feat(ghidra): admit explicit DOS COM analysis

Carry caller-selected COM interpretation through CLI, MCP and target
identity, seed real-mode entry/context before Ghidra analysis, and verify
complete loaded bytes, source mappings and measured register context.
Keep original binaries unchanged and PSP/runtime coverage explicit.

Assisted-by: Nitori (gensokyo-skills:nitori-reverse-engineering)

* fix(verification): validate COM package selection before allocating fixtures
2026-10-06 16:26:40 +08:00
Kaoru0822 fd3282a87e fix(native): select concrete arm64e Mach-O slices 2026-10-06 01:25:11 -07:00
Kaoru0822 a4e57366dd fix(process): honor disabled PID normalization in samples 2026-10-06 01:22:45 -07:00
Rudy Mizrahi CelekliandGitHub d565ecdc25 fix(reference): read linked worktree commit provenance (#677)
Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>
2026-10-06 16:18:42 +08:00
Rudy Mizrahi CelekliandGitHub 8189081511 fix(browser): keep bare module locations unresolved (#676)
Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>
2026-10-06 16:18:36 +08:00
Kaoru0822andGitHub 7f1fa64019 fix(javascript): read source-map directives only from comments (#672) 2026-10-06 16:18:25 +08:00
Rudy Mizrahi CelekliandGitHub c8aed4740d fix(reference): preserve unresolved absolute module specifiers (#670)
Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>
2026-10-06 16:18:17 +08:00
Rudy Mizrahi CelekliandGitHub fa02df9ad3 fix(native): retain spaced symbols in dyld inventory (#669)
Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>
2026-10-06 16:18:09 +08:00
Rudy Mizrahi CelekliandGitHub ddea06360a fix(dotnet): preserve leading Unicode content in metadata strings (#667)
Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>
2026-10-06 16:18:01 +08:00
Rudy Mizrahi CelekliandGitHub 94cc8475e0 fix(javascript): preserve primitive addition coercion (#666)
Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>
2026-10-06 16:17:55 +08:00
Kaoru0822andGitHub 1a24be574d fix(reference): recognize CMake build manifests (#665) 2026-10-06 16:17:50 +08:00
Kaoru0822andGitHub 217e8cf59f Merge pull request #700 from kaoru0822-kitauji/fix/json-shape-collation
fix(comparison): break JSON shape collation ties
2026-10-06 01:10:26 -07:00
Kaoru0822andGitHub a55b5bb8ee Merge pull request #698 from kaoru0822-kitauji/fix/export-container-coverage
fix(comparison): retain container-only export shape paths
2026-10-06 01:10:13 -07:00
Kaoru0822andGitHub ba35b5509d Merge pull request #696 from kaoru0822-kitauji/fix/reference-computed-require
fix(reference): distinguish computed require member names
2026-10-06 01:09:56 -07:00
Kaoru0822andGitHub 11d0ef2e09 Merge pull request #695 from kaoru0822-kitauji/fix/reference-parser-recovery
fix(reference): retain recovered parser diagnostics
2026-10-06 01:09:40 -07:00
Kaoru0822 805c338f36 fix(comparison): break JSON shape collation ties 2026-10-06 01:01:16 -07:00
N0zoM1z0andGitHub a6a8f67649 feat(ghidra): verify DOS load images and expose memory evidence (#697)
* feat(ghidra): verify DOS load images and expose memory evidence

Verify measured source bytes, mapped regions, fixups and entries against
the immutable MZ snapshot, retaining independent checks and raw evidence.
Expose loaded byte reads and authoritative original file offsets through
both CLI and MCP, with focused and actual Ghidra DOS verification.

Assisted-by: Nitori (gensokyo-skills:nitori-reverse-engineering)

* fix(cli): describe memory inspection arguments

* test(ghidra): align bridge fixtures and CLI capability accounting
2026-10-06 15:48:48 +08:00
Kaoru0822 7864d665e1 fix(comparison): retain container-only export shape paths 2026-10-06 00:42:19 -07:00
Kaoru0822 df6e476d67 fix(reference): distinguish computed require member names 2026-10-06 00:26:08 -07:00
Kaoru0822 ed3a7f070c fix(reference): retain recovered parser diagnostics 2026-10-06 00:17:04 -07:00
Kaoru0822andGitHub 132a3a46be Merge pull request #694 from kaoru0822-kitauji/fix/dockerfile-language-boundary
fix(reference): bound Dockerfile language detection
2026-10-06 00:10:16 -07:00
Kaoru0822andGitHub e828acce0e Merge pull request #692 from kaoru0822-kitauji/fix/reference-test-stems
fix(reference): classify test suffixes before extensions
2026-10-06 00:07:24 -07:00
Kaoru0822 53fa55937f fix(reference): bound Dockerfile language detection 2026-10-06 00:03:29 -07:00
Kaoru0822andGitHub e60aa11108 Merge pull request #691 from kaoru0822-kitauji/fix/javascript-line-terminators
fix(javascript): count all source line terminators
2026-10-05 23:59:26 -07:00
Kaoru0822 8b228ae701 fix(reference): classify test suffixes before extensions 2026-10-05 23:56:24 -07:00
Kaoru0822 03bc6d36db fix(javascript): count all source line terminators 2026-10-05 23:49:27 -07:00
Kaoru0822andGitHub b6c21b1db5 Merge pull request #683 from morluto/docs/research-trendshift-badge
docs: add the official Trendshift badge to README headers
2026-10-05 23:32:36 -07:00
Kaoru0822andGitHub 433ebda8b4 Merge pull request #682 from kaoru0822-kitauji/fix/disable-unmanaged-skill-sync
fix(cli): disable unmanaged skill synchronization
2026-10-05 23:32:18 -07:00
Kaoru0822 2c1bf92010 fix(cli): disable unmanaged skill synchronization 2026-10-05 23:27:46 -07:00
N0zoM1z0 7d4ed59816 docs: add the official Trendshift badge to README headers 2026-10-06 06:27:12 +00:00
I Made Ocy Darma PutraandGitHub 7f1ae42f71 feat(setup): support Command Code MCP registration (#645)
Configure Command Code's user-scope MCP config (~/.commandcode/mcp.json)
with an explicit stdio registration ({ transport, enabled, command, args })
under mcpServers, matching the shape Command Code writes itself.

Adds the commandcode setup client and dialect, detection/alignment support,
README/docs entries, and regenerated product catalog.
2026-10-06 14:15:59 +08:00
Kaoru0822andGitHub 6ad62cec6a Merge pull request #663 from kaoru0822-kitauji/fix/semantic-candidate-relevance
fix(javascript): scope candidate ambiguity to query traversal
2026-10-05 23:06:33 -07:00
N0zoM1z0andGitHub 39db9fe424 docs: align MCP discovery and skill guidance with the stable catalog (#664) 2026-10-06 14:01:43 +08:00
Kaoru0822andGitHub c3d013b2fd Merge pull request #659 from kaoru0822-kitauji/fix/function-collation-ties
fix(comparison): break function collection collation ties
2026-10-05 22:58:54 -07:00
Kaoru0822andGitHub a5d2986b1e Merge pull request #657 from kaoru0822-kitauji/fix/reference-dynamic-imports
fix(reference): retain dynamic import relationships
2026-10-05 22:55:27 -07:00
Kaoru0822andGitHub 6a37346acb Merge pull request #652 from kaoru0822-kitauji/fix/dispatcher-build-recovery
fix(cli): include build step in missing-runtime recovery
2026-10-05 22:55:11 -07:00
Kaoru0822 f94fc7967b fix(javascript): scope candidate ambiguity to query traversal 2026-10-05 22:51:47 -07:00
N0zoM1z0andGitHub 88a3c3f8a4 test(hopper): synchronize startup cancellation with launcher readiness (#662) 2026-10-06 13:51:45 +08:00
Kaoru0822andGitHub 8dd1d84471 docs(installation): pin manual MCP registration to the release version (#658) 2026-10-06 13:50:08 +08:00
Kaoru0822andGitHub 5802ef8746 Merge pull request #651 from kaoru0822-kitauji/fix/node-runtime-engine-alignment
fix(setup): align Node runtime checks with package engines
2026-10-05 22:45:21 -07:00
Kaoru0822 3aaf7e2c54 fix(comparison): break function collection collation ties 2026-10-05 22:39:03 -07:00
N0zoM1z0andGitHub fc80ea88df docs: correct CLI examples and documentation checks (#655) 2026-10-06 13:34:22 +08:00
Kaoru0822 b89de8feab fix(reference): retain dynamic import relationships 2026-10-05 22:32:36 -07:00
Kaoru0822 ae72abd019 fix(cli): include build step in missing-runtime recovery 2026-10-05 22:19:35 -07:00
Kaoru0822 ea0b733687 fix(setup): align Node runtime checks with package engines 2026-10-05 22:13:22 -07:00
N0zoM1z0andGitHub 19f8cddfd6 fix(ghidra): preserve request and shutdown failure diagnostics (#647) 2026-10-06 12:13:52 +08:00
N0zoM1z0andGitHub 9f42495d11 fix(javascript): hash graph and evidence JSON incrementally (#646) 2026-10-06 11:54:55 +08:00
morlutoandGitHub 9b392bb2f8 chore(deps): finish toolchain upgrades and drop dead weight (#644)
* chore(deps): finish toolchain upgrades and drop dead weight

pino 9 to 10, @types/node 24 to 26, oxlint 1.73 to 1.87, knip 6.26
to 6.39, turbo 2.10 to 2.11. Narrow engines to supported majors
(22/24/26; vitest 5 refuses Node 25). Scope no-var-requires off for
Electron CJS hooks and fixtures.

Remove TypeDoc: incompatible with TypeScript 7 at install and
runtime, used by nothing in any gate. Drop the dep, docs:api
workflow, typedoc.json, CI artifact step, and related docs.

Replace graphology with a local call-graph adjacency plus BFS: the
only consumer is call-path search, and graphology-types ships no
types entry for TS7 NodeNext resolution. Delete both graphology
dependencies.

Remove dead re-exports newly flagged by knip 6.39.

* chore: drop stale typedoc and replay references

Remove the docs:api release-checklist step, the orphaned docs/api
ignore entry, and the nonexistent replay glob from the adapters
project.
2026-10-06 06:02:02 +08:00
morlutoandGitHub 5f27e02fae refactor(runtime): name all silent catch causes without changing diagnostics (#637)
* refactor(domain): split error taxonomy into thematic modules

Move each error family out of domain/errors.ts into its own module
(base, core, provider selection/adapter, browser observation,
artifact, evidence, unknown registry, hopper, configuration) and
relocate AnalysisErrorProjection to analysisErrorProjection.
Migrate all 162 importers to the owning modules and delete
errors.ts. No re-export shims; behavior is unchanged.

* refactor(runtime): name all silent catch causes without changing diagnostics

Bind cause in every bare catch and unhandled rejection across src/.
Real failures preserve the cause for logging; best-effort cleanup
carries an explicit comment. Caller-visible and Evidence strings are
byte-identical to before.
2026-10-06 05:58:46 +08:00
morlutoandGitHub 735c10059c refactor(domain): split error taxonomy into thematic modules (#636)
Move each error family out of domain/errors.ts into its own module
(base, core, provider selection/adapter, browser observation,
artifact, evidence, unknown registry, hopper, configuration) and
relocate AnalysisErrorProjection to analysisErrorProjection.
Migrate all 162 importers to the owning modules and delete
errors.ts. No re-export shims; behavior is unchanged.
2026-10-06 05:57:38 +08:00
morluto 77799e6c90 fix(ci): upload Vitest blob reports from current path 2026-10-06 05:54:40 +08:00
morluto 965d0b35f9 chore(deps): remove incompatible TypeDoc generator 2026-10-06 05:46:44 +08:00
morlutoandGitHub 5295d56b10 refactor(contracts): split tool contracts by family (#634)
Move official, enhanced, and session contract arrays with their
builders into officialToolContracts, enhancedToolContracts, and
sessionToolContracts. toolContracts keeps the ordered assembly and
resolver. Migrate all importers including catalog scripts. No
re-export shims; generated catalog output is unchanged.
2026-10-06 05:20:11 +08:00
morlutoandGitHub dee8853fde chore(deps): upgrade typescript, vitest, and MCP SDK to latest (#633)
typescript 5.9.3 to 7.0.2, vitest 4.1.10 to 5.0.3 (plus
@vitest/coverage-v8 and @fast-check/vitest 0.5.0 for peer compat),
@Modelcontextprotocol/client and server 2.0.0 to 2.3.1. Migrate the
removed describe.sequential to concurrent:false and regenerate
package metadata and product catalog.

Also restore byte-faithful reads in parseCliJsonInput: the safeJson
migration dropped the fatal UTF-8 check from #613. Vitest 5 requires
Node 22/24/26+, so verify on Node 24 (repo-pinned toolchain).
2026-10-06 05:15:17 +08:00
morlutoandGitHub 494d4db6d9 refactor(cli): collapse duplicate CLI layer into src/cli (#630)
Move root cli*Commands and cliSetup into src/cli, delete the
forwarding layer, point src/cli.ts and tests at the owners. No
forwarding shims.
2026-10-06 05:04:25 +08:00
morlutoandGitHub e7f54b3310 refactor(runtime): centralize safe JSON parsing and preserve error causes (#629)
* refactor(domain): consolidate canonical ordering and digest helpers (#624)

* refactor(domain): consolidate canonical ordering and digest helpers

Single owner for code-point ordering (domain/canonicalOrdering.ts)
and canonical JSON digests (domain/comparisonSemantics.ts). Delete
all local compareCodePoints/compareText/digestCanonical duplicates
and migrate every importer. No re-export shims.

* fix(ci): allow slower real browser startup

* chore(config): remove dead eslint, dedupe scripts, cacheable turbo tasks

Delete eslint.config.js (oxlint is the linter), drop lint:dead alias,
pin smol-toml, fold jscpd/scan:todos into check:pr, make test:run
cacheable, align oxlint ignores.

* fix(config): hash all test inputs for cached runs

* docs: fix architecture diagram and pretty-print tool catalog

Drop dangling REPLAY edges, add dotnet/reference/error/evaluation
nodes. Emit 2-space JSON from the catalog generator and regenerate.

* test: extract shared fixtures, drop knip carve-outs

Dedupe android/apple session tests, bundler adapter headers, and
reconstruction helpers into tests/support fixtures. Delete unused
type aliases and the knip ignoreIssues block. Lower jscpd threshold
2.7 to 2.5.

* refactor(app): split Setup and ProcessOwnership modules

Extract SetupTypes/SetupHost from Setup.ts and move observation
helpers into ProcessOwnershipObservation/ProcessTree. Migrate all
importers including CLI commands. No re-export shims.

* refactor(runtime): centralize safe JSON parsing and preserve error causes

Add domain/safeJson.safeParseJson and migrate all raw JSON.parse
call sites. Name catch causes and preserve failure reasons instead
of swallowing; annotate genuine best-effort cleanup.

* fix(runtime): retain JSON parse error causes
2026-10-06 05:00:54 +08:00
morlutoandGitHub 3c84080aab refactor(app): split Setup and ProcessOwnership modules (#628)
* refactor(domain): consolidate canonical ordering and digest helpers (#624)

* refactor(domain): consolidate canonical ordering and digest helpers

Single owner for code-point ordering (domain/canonicalOrdering.ts)
and canonical JSON digests (domain/comparisonSemantics.ts). Delete
all local compareCodePoints/compareText/digestCanonical duplicates
and migrate every importer. No re-export shims.

* fix(ci): allow slower real browser startup

* chore(config): remove dead eslint, dedupe scripts, cacheable turbo tasks

Delete eslint.config.js (oxlint is the linter), drop lint:dead alias,
pin smol-toml, fold jscpd/scan:todos into check:pr, make test:run
cacheable, align oxlint ignores.

* fix(config): hash all test inputs for cached runs

* docs: fix architecture diagram and pretty-print tool catalog

Drop dangling REPLAY edges, add dotnet/reference/error/evaluation
nodes. Emit 2-space JSON from the catalog generator and regenerate.

* test: extract shared fixtures, drop knip carve-outs

Dedupe android/apple session tests, bundler adapter headers, and
reconstruction helpers into tests/support fixtures. Delete unused
type aliases and the knip ignoreIssues block. Lower jscpd threshold
2.7 to 2.5.

* refactor(app): split Setup and ProcessOwnership modules

Extract SetupTypes/SetupHost from Setup.ts and move observation
helpers into ProcessOwnershipObservation/ProcessTree. Migrate all
importers including CLI commands. No re-export shims.
2026-10-06 05:00:32 +08:00
morlutoandGitHub 55e5eb090b test: extract shared fixtures, drop knip carve-outs (#627)
* refactor(domain): consolidate canonical ordering and digest helpers (#624)

* refactor(domain): consolidate canonical ordering and digest helpers

Single owner for code-point ordering (domain/canonicalOrdering.ts)
and canonical JSON digests (domain/comparisonSemantics.ts). Delete
all local compareCodePoints/compareText/digestCanonical duplicates
and migrate every importer. No re-export shims.

* fix(ci): allow slower real browser startup

* chore(config): remove dead eslint, dedupe scripts, cacheable turbo tasks

Delete eslint.config.js (oxlint is the linter), drop lint:dead alias,
pin smol-toml, fold jscpd/scan:todos into check:pr, make test:run
cacheable, align oxlint ignores.

* fix(config): hash all test inputs for cached runs

* docs: fix architecture diagram and pretty-print tool catalog

Drop dangling REPLAY edges, add dotnet/reference/error/evaluation
nodes. Emit 2-space JSON from the catalog generator and regenerate.

* test: extract shared fixtures, drop knip carve-outs

Dedupe android/apple session tests, bundler adapter headers, and
reconstruction helpers into tests/support fixtures. Delete unused
type aliases and the knip ignoreIssues block. Lower jscpd threshold
2.7 to 2.5.
2026-10-06 05:00:16 +08:00
morlutoandGitHub 5e7f35c7c3 docs: fix architecture diagram and pretty-print tool catalog (#626)
* refactor(domain): consolidate canonical ordering and digest helpers (#624)

* refactor(domain): consolidate canonical ordering and digest helpers

Single owner for code-point ordering (domain/canonicalOrdering.ts)
and canonical JSON digests (domain/comparisonSemantics.ts). Delete
all local compareCodePoints/compareText/digestCanonical duplicates
and migrate every importer. No re-export shims.

* fix(ci): allow slower real browser startup

* chore(config): remove dead eslint, dedupe scripts, cacheable turbo tasks

Delete eslint.config.js (oxlint is the linter), drop lint:dead alias,
pin smol-toml, fold jscpd/scan:todos into check:pr, make test:run
cacheable, align oxlint ignores.

* fix(config): hash all test inputs for cached runs

* docs: fix architecture diagram and pretty-print tool catalog

Drop dangling REPLAY edges, add dotnet/reference/error/evaluation
nodes. Emit 2-space JSON from the catalog generator and regenerate.
2026-10-06 05:00:01 +08:00
morlutoandGitHub 9c10a64f87 chore(config): remove dead eslint, dedupe scripts, cacheable turbo tasks (#625)
* refactor(domain): consolidate canonical ordering and digest helpers (#624)

* refactor(domain): consolidate canonical ordering and digest helpers

Single owner for code-point ordering (domain/canonicalOrdering.ts)
and canonical JSON digests (domain/comparisonSemantics.ts). Delete
all local compareCodePoints/compareText/digestCanonical duplicates
and migrate every importer. No re-export shims.

* fix(ci): allow slower real browser startup

* chore(config): remove dead eslint, dedupe scripts, cacheable turbo tasks

Delete eslint.config.js (oxlint is the linter), drop lint:dead alias,
pin smol-toml, fold jscpd/scan:todos into check:pr, make test:run
cacheable, align oxlint ignores.

* fix(config): hash all test inputs for cached runs
2026-10-06 04:59:49 +08:00
morlutoandGitHub ba3869c597 refactor(domain): consolidate canonical ordering and digest helpers (#624)
* refactor(domain): consolidate canonical ordering and digest helpers

Single owner for code-point ordering (domain/canonicalOrdering.ts)
and canonical JSON digests (domain/comparisonSemantics.ts). Delete
all local compareCodePoints/compareText/digestCanonical duplicates
and migrate every importer. No re-export shims.

* fix(ci): allow slower real browser startup
2026-10-06 04:55:26 +08:00
morlutoandGitHub 38b293329c refactor(native): extract FAT header format switch in Mach-O slice selection (#632)
Replace inline magic comparisons with an exhaustive fatHeaderFormat
switch and add a regression test locking in rejection of 32-bit
slice payloads inside little-endian containers. Behavior-preserving:
the new test passes on the old implementation.
2026-10-06 04:36:13 +08:00
574 changed files with 18396 additions and 5230 deletions
+43 -18
View File
@@ -105,7 +105,7 @@ jobs:
if: ${{ !cancelled() }}
with:
name: vitest-report-${{ strategy.job-index }}
path: .vitest-reports/*
path: .vitest/blob/*
include-hidden-files: true
if-no-files-found: error
overwrite: true
@@ -157,7 +157,7 @@ jobs:
- uses: actions/download-artifact@v4
if: needs.changes.outputs.code == 'true' && success()
with:
path: .vitest-reports
path: .vitest/blob
pattern: vitest-report-*
merge-multiple: true
- name: Merge coverage, JUnit, and timing reports
@@ -215,9 +215,30 @@ jobs:
- name: Verify fixtures from a clean checkout
run: npm run verify:fixtures
windows-native-build:
name: Build bundled Windows x64 native controls
needs: changes
if: github.event_name == 'push' || needs.changes.outputs.package == 'true'
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
- name: Prepare cross compiler
run: sudo apt-get update && sudo apt-get install --no-install-recommends -y g++-mingw-w64-x86-64
- run: npm run build:windows-native
- run: npm run verify:windows-native:artifact
- uses: actions/upload-artifact@v4
with:
name: windows-native-controls
path: native/windows/build/
if-no-files-found: error
package-e2e:
name: Package/install integration (${{ matrix.os }})
needs: changes
needs: [changes, windows-native-build]
if: github.event_name == 'push' || needs.changes.outputs.package == 'true'
strategy:
fail-fast: false
@@ -231,6 +252,11 @@ jobs:
node-version-file: .nvmrc
cache: npm
- run: npm ci
- uses: actions/download-artifact@v4
with:
name: windows-native-controls
path: native/windows/build/
- run: npm run verify:windows-native:artifact
- run: npm run verify:package
apple-artifacts:
@@ -302,7 +328,7 @@ jobs:
windows-curated:
name: Windows capability and package lane
needs: changes
needs: [changes, windows-native-build]
if: github.event_name == 'push' || needs.changes.outputs.package == 'true'
runs-on: windows-latest
timeout-minutes: 25
@@ -315,6 +341,11 @@ jobs:
- run: npm ci
- run: npm run build:cached
- run: npm run typecheck
- uses: actions/download-artifact@v4
with:
name: windows-native-controls
path: native/windows/build/
- run: npm run verify:windows-native:artifact
- name: Record named Windows host capabilities
run: node scripts/windows-capabilities.mjs | Out-File -Encoding utf8NoBOM windows-capabilities.json
- name: Validate Windows host capability report
@@ -327,18 +358,14 @@ jobs:
# ignores unmatched paths, so a stale entry would otherwise report green
# while skipping coverage.
#
# Every path here must pass on windows-latest WITHOUT verified Windows
# native authority. src/ghidra/GhidraProvider.test.ts,
# src/ghidra/GhidraProvider.behavior.test.ts successors, and
# tests/boundary/process/providerProcess.test.ts are deliberately absent:
# they require Job Object process ownership and private-runtime DACL
# enforcement, which this runner does not provide by design. Those claims
# belong behind the same approval boundary as the real Ghidra Windows
# workflow, not in the default lane.
# The matching native artifact establishes real Job Object and private
# runtime boundaries for these fixtures. Ghidra and Java are not needed;
# real engine claims remain in the separate controlled-provider workflow.
- name: Run curated Windows capability tests
run: >-
npx vitest run --coverage.enabled=false
tests/boundary/filesystem/binaryTarget.test.ts
tests/boundary/filesystem/setupUnavailableProvider.test.ts
tests/boundary/filesystem/asarInventoryFreshness.test.ts
tests/composition/javascript-applications/javascriptArtifactReconstruction.test.ts
tests/conformance/providers/ghidra/windowsCapabilities.test.ts
@@ -347,6 +374,9 @@ jobs:
tests/boundary/providers/ghidra/ghidraTransport.test.ts
tests/boundary/providers/ghidra/ghidraTargetSnapshot.test.ts
tests/boundary/providers/ghidra/ghidraLauncher.test.ts
src/windows/WindowsNativeLoader.test.ts
src/windows/WindowsOwnedProcess.test.ts
src/ghidra/GhidraLauncherEnvironment.test.ts
src/process/ProcessOwnership.test.ts
src/process/ProcessOwnership.part2.test.ts
src/process/ProcessOwnership.part3.test.ts
@@ -354,6 +384,7 @@ jobs:
src/application/Update.test.ts
tests/process-global/updateMaintenance.test.ts
tests/conformance/providers/ghidra/realGhidraWindowsWorkflow.test.ts
- run: npm run verify:windows-native
- run: npm run verify:package:windows
- uses: actions/upload-artifact@v4
if: always()
@@ -374,9 +405,3 @@ jobs:
cache: npm
- run: npm ci
- run: npm run docs:check
- run: npm run docs:api:cached
- uses: actions/upload-artifact@v4
with:
name: api-docs
path: build/api-docs
retention-days: 14
+33 -1
View File
@@ -11,9 +11,29 @@ permissions:
contents: read
jobs:
native-artifact:
name: Build matching Windows native artifact
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
- name: Prepare cross compiler
run: sudo apt-get update && sudo apt-get install --no-install-recommends -y g++-mingw-w64-x86-64
- run: npm run build:windows-native
- run: npm run verify:windows-native:artifact
- uses: actions/upload-artifact@v4
with:
name: real-ghidra-windows-native
path: native/windows/build/
if-no-files-found: error
verify:
name: Real Ghidra 12.1.4 Windows x64 PE proof
if: github.ref == 'refs/heads/main'
needs: native-artifact
environment: real-ghidra-windows
runs-on: [self-hosted, Windows, x64, ghidra-12-1-2]
timeout-minutes: 20
@@ -23,13 +43,25 @@ jobs:
with:
node-version-file: .nvmrc
- run: npm ci
- uses: actions/download-artifact@v4
with:
name: real-ghidra-windows-native
path: native/windows/build/
- run: npm run verify:windows-native:artifact
- run: npm run verify:windows-native
- name: Verify all admitted Windows Ghidra operations
env:
REA_ANALYSIS_PROVIDER: ghidra
run: npm run verify:ghidra:windows | Tee-Object -FilePath windows-ghidra-proof.log
- name: Verify ordinary-user CLI and MCP operations
env:
REA_ANALYSIS_PROVIDER: ghidra
run: npm run verify:ghidra:windows:package | Tee-Object -FilePath windows-ghidra-package-proof.log
- uses: actions/upload-artifact@v4
if: always()
with:
name: windows-ghidra-proof
path: windows-ghidra-proof.log
path: |
windows-ghidra-proof.log
windows-ghidra-package-proof.log
retention-days: 30
+6
View File
@@ -108,6 +108,12 @@ jobs:
- run: npm ci
- name: Prepare Windows native build toolchain
run: sudo apt-get update && sudo apt-get install --no-install-recommends -y g++-mingw-w64-x86-64
- name: Build and verify bundled Windows native controls
run: npm run build:windows-native && npm run verify:windows-native:artifact
- name: Verify packaged release before publishing
run: npm run verify:package
-1
View File
@@ -6,7 +6,6 @@ __pycache__/
# Distribution
dist/
build/
docs/api/
node_modules
*.egg-info/
*.egg
+2 -2
View File
@@ -1,6 +1,6 @@
{
"_comment": "Test files are intentionally NOT excluded: the gate used to report zero clones because it skipped **/*.test.ts, hiding all test-tree duplication. Current actual is ~2.6% lines across src+ and tests/, down from 3.4% when tests were included. Lower this as duplication is removed.",
"threshold": 2.7,
"_comment": "Test files are intentionally NOT excluded: the gate used to report zero clones because it skipped **/*.test.ts, hiding all test-tree duplication. Current actual is ~2.4% lines across src+ and tests/, down from 3.4% when tests were included. Lower this as duplication is removed.",
"threshold": 2.5,
"reporters": ["consoleFull"],
"ignore": [
"node_modules/**",
+21 -1
View File
@@ -17,6 +17,15 @@
"no-var-requires": "error"
},
"overrides": [
{
"files": [
"scripts/electron-active-hook*.cjs",
"tests/conformance/readiness/electron/*.js"
],
"rules": {
"no-var-requires": "off"
}
},
{
"files": [
"src/{contracts,domain,server}/**/*.ts",
@@ -120,5 +129,16 @@
"node": true,
"es2023": true
},
"ignorePatterns": ["dist", "node_modules", "docs/api", ".codex", ".devin"]
"ignorePatterns": [
"dist",
"build",
"node_modules",
"docs/api",
"coverage",
".turbo",
".cache",
".codex",
".devin",
".factory"
]
}
+13 -2
View File
@@ -2,7 +2,7 @@
## Product Direction
REA exposes reverse-engineering tools through a CLI and MCP server. Hopper and the bring-your-own Ghidra adapter are operation-capable deep binary-analysis providers. Ghidra is supported on Linux x64 and macOS x64/arm64 with matching native decompiler tools, and has an experimental Windows x64 P0 boundary for approved native x86-64 PE applications; it supplies admitted read-only inventory and function-analysis operations but no GUI or mutation authority. Keep provider-specific code out of the domain and application layers.
REA exposes reverse-engineering tools through a CLI and MCP server. Hopper and the bring-your-own Ghidra adapter are operation-capable deep binary-analysis providers. Ghidra is supported on Linux x64 and macOS x64/arm64 with matching native decompiler tools, and has an experimental Windows x64 P0 boundary for approved native x86-64 PE applications; on Linux and macOS it supplies inventory, function analysis, and atomic function annotation edits in an ephemeral database, without modifying executable bytes or controlling a GUI. Windows P0 has no mutation authority. Keep provider-specific code out of the domain and application layers.
Prioritize:
@@ -35,7 +35,7 @@ REA is a layered ESM TypeScript application. Dependencies flow inward from pure
- `npm run check:changed`: run cached static checks and source tests affected since the branch merge base (default `origin/main`).
- `npm run check:fast`: run cached typecheck and lint checks.
- `npm run check:pr`: opt into the complete local deterministic gate and generated-document checks for broad changes; CI owns full coverage. Routine iterations need focused tests and relevant checks, not the whole gate each time.
- `npm run docs:check`: check committed generated documents; `npm run docs:api:cached` separately renders API HTML when needed.
- `npm run docs:check`: check committed generated documents; `npm run docs:generate` regenerates them.
- For provider-dependent changes, see [docs/testing.md](docs/testing.md) and run the matching real-provider verification.
- Keep each verification lane's prerequisites limited to the claim it checks. Use host-native fixtures for host/provider acceptance; put optional cross-target formats and their external toolchains in a separate lane. Preflight required commands and report the missing dependency and lane clearly.
@@ -94,3 +94,14 @@ Keep tool catalogs complete and self-describing; prefer capability- and session-
## Commit & Pull Request Guidelines
Use Conventional Commit subjects because Release Please derives versions and changelogs from them. Examples: `feat: add historical source import`, `fix(process): stop timers after exit`, and `docs: update architecture`. Use `!` or a `BREAKING CHANGE:` footer for breaking changes. Pull request titles must follow the same format because squash merges use the title as the release commit. Pull requests should describe contract or behavior changes, list verification commands, link issues, and include sanitized MCP examples when schemas change. State whether real Hopper/Ghidra verification was performed. Never commit binaries, Hopper or Ghidra project documents, credentials, `dist/`, `node_modules/`, or local planning artifacts (e.g. `.codex/`).
<!-- BEGIN:turborepo-agent-rules -->
# This is NOT the Turborepo you know
Turborepo configuration, task behavior, and CLI commands can vary between installed versions and may differ from your training data. Resolve the `turbo` package from this file's directory or relevant workspace; in monorepos, it may not be visible from the repository root. For example, run `node -p "require.resolve('turbo/package.json')"` from a workspace that depends on `turbo`.
Read `docs/README.md` inside that installed package first, then read the relevant pages from its `docs/` directory before changing Turborepo configuration or commands. Heed deprecation notices. These bundled docs match the installed package version and are available without network access.
This block is written and re-added by `turbo` before repository-scoped commands when an AI agent is detected. In the Turborepo source repository, its template is defined in `crates/turborepo-cli/src/cli/agent_guidance.rs`. Removing the managed block while updates are enabled means a later qualifying invocation will add it again. Set `"agentGuidance": false` in the root `turbo.json` or `turbo.jsonc` to opt out; this does not remove an existing block. Keep the block committed with your work to avoid an uncommitted change on the next agent invocation.
<!-- END:turborepo-agent-rules -->
+4 -5
View File
@@ -20,7 +20,7 @@ Turbo. Turbo caches deterministic builds and static checks across Git
worktrees. After a package, lockfile, or managed-skill version change, run
`npm run metadata:generate` before building.
Keep dependencies flowing inward through the existing domain, contracts, provider, application, server, and adapter layers. Parse unknown values at process and protocol boundaries, model expected failures with `Result`, and preserve the canonical tool inventory defined by `TOOL_CONTRACTS` unless a deliberate contract change updates every verifier, generated catalog artifact, and snapshot. Prefer capability- and session-scoped tool advertisement over schema truncation.
Keep dependencies flowing inward through the existing domain, contracts, provider, application, server, and adapter layers. Parse unknown values at process and protocol boundaries, model expected failures with `Result`, and preserve the canonical tool inventory defined by `TOOL_CONTRACTS` unless a deliberate contract change updates every verifier, generated catalog artifact, and snapshot. Keep tool discovery complete and report capability- and session-scoped availability through `binary_session`.
## Development feedback and PR verification
@@ -52,9 +52,8 @@ require the matching real-provider `verify:*` lane.
Formatting uses Oxfmt and the committed `.oxfmtrc.json`; generated sources use
the same configuration. Pre-commit formats and lints staged files; pre-push runs
`check:fast`.
`docs:check` checks committed generated metadata without rendering API HTML.
`docs:generate` regenerates those files; render API HTML separately with
`npm run docs:api:cached`. PR CI renders and uploads the `api-docs` artifact.
`docs:check` checks committed generated metadata. `docs:generate` regenerates
those files, and the docs CI lane checks them.
Real-provider execution remains uncached; deterministic builds use Turbo.
Local `npm test` runs every deterministic Vitest project without coverage or
@@ -101,7 +100,7 @@ Describe the behavior change and verification performed in the pull request. Nev
## Maintainer release checklist
Run `npm run check:pr`, `npm run docs:api:cached`, the isolated package verifier, package dry run, and two-target real-Hopper verifier described above. Build a local tarball and exercise the executable through the package boundary:
Run `npm run check:pr`, the isolated package verifier, package dry run, and two-target real-Hopper verifier described above. Build a local tarball and exercise the executable through the package boundary:
```bash
npm pack
+21 -17
View File
@@ -15,6 +15,8 @@
[![MIT license](https://img.shields.io/badge/license-MIT-f4c430?style=flat-square)](LICENSE)
[![Discord](https://img.shields.io/discord/1556595354999332884?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/GkcryMnJDM)
<a href="https://trendshift.io/repositories/82054?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-82054" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/82054/weekly?language=TypeScript" alt="morluto/rea | Trendshift" width="250" height="55" /></a>
[Quick start](#quick-start) · [Current status](#current-status) · [Investigation model](#the-investigation-model) · [Tool catalog](#tool-catalog-for-investigation) · [Roadmap](#roadmap) · [How it works](#how-it-works)
<code>npx rea-agents setup</code>
@@ -110,7 +112,7 @@ Setup shows its changes before applying them and backs up existing configuration
After setup, restart your agent and [describe the app or feature](#just-ask-your-agent) you want to understand. Hopper can run in demo mode; if it shows a first-run prompt, choose the demo or enter an existing license.
REA supports Claude Code, Claude Desktop, Codex, Cursor, Gemini CLI, Windsurf, Devin, OpenCode, Antigravity, GitHub Copilot CLI, and VS Code. Existing REA registrations are selected by default during setup; other detected agents remain unselected until chosen. Other agents can use the [manual MCP configuration](#manual-mcp-configuration).
REA supports Claude Code, Claude Desktop, Codex, Cursor, Gemini CLI, Windsurf, Devin, OpenCode, Antigravity, GitHub Copilot CLI, Command Code, and VS Code. Existing REA registrations are selected by default during setup; other detected agents remain unselected until chosen. Other agents can use the [manual MCP configuration](#manual-mcp-configuration).
### From the terminal with npx
@@ -144,12 +146,12 @@ Update either installation with `rea update`.
- macOS 12 or newer
- Ubuntu 24.04+, Fedora 41+, or 64-bit Arch Linux
- Node.js 22.19+ or 24.11+ (including newer releases)
- Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+
- npm; REA does not require or install a particular npm version
Native binary analysis requires [Hopper](https://www.hopperapp.com/) or [Ghidra](#ghidra-read-only-analysis-provider). Hopper is separate software with its own license; its demo supports analysis with vendor-defined limits. REA can use Ghidra that you have already installed.
Native binary analysis requires [Hopper](https://www.hopperapp.com/) or [Ghidra](#ghidra-analysis-provider). Hopper is separate software with its own license; its demo supports analysis with vendor-defined limits. REA can use Ghidra that you have already installed.
Windows Ghidra support is experimental and currently unavailable. The required Windows process ownership, private-directory permissions, and safe-path checks are not implemented. See [Windows Ghidra P0](docs/windows-ghidra-p0.md) for the remaining requirements.
Windows Ghidra support is experimental for native x86-64 PE applications on local NTFS. The package bundles native Job Object, private-DACL, and path-admission controls. See [Windows Ghidra P0](docs/windows-ghidra-p0.md) for prerequisites and verified scope.
If something is not working, run:
@@ -182,7 +184,7 @@ Install the missing packages and rerun `rea setup`. The Linux demo needs Xvfb, P
REA defaults `HOPPER_LAUNCHER_PATH` to `/Applications/Hopper Disassembler.app/Contents/MacOS/hopper` on macOS and `/opt/hopper/bin/Hopper` on Linux. Explicit configuration always takes precedence.
### Ghidra read-only analysis provider
### Ghidra analysis provider
Already use Ghidra? REA can connect it to your agent on Linux x64 or macOS x64/arm64. It requires **Ghidra 12.1.4** and a **64-bit JDK 21**. On macOS, your Ghidra installation must also include the native decompiler for your architecture.
@@ -198,13 +200,13 @@ rea providers --json
Setup checks the installations and saves their paths in your selected agents' configuration after approval. Ghidra and Java must already be installed; REA does not download or change them.
The adapter exposes **22 read-only operations** for functions, strings, symbols, assembly, decompilation, calls, references, instructions, and data types. These also support REA's overview, search, call-graph, and function-analysis workflows. Ghidra does not provide GUI controls or annotation changes through REA.
The adapter exposes inventory, function, memory and load-image inspection, plus atomic function annotation edits on Linux and macOS. `annotate_native_function` edits names and entry comments in the session database and returns a refreshed function dossier; executable bytes stay unchanged. Ghidra does not provide GUI controls through REA.
REA analyzes a temporary copy of the target and removes the temporary project when the session closes. Results identify what Ghidra observed and what it could not resolve. Decompilation produces pseudocode rather than the original source.
Ghidra also imports DOS MZ executables with an explicit 16-bit x86 real-mode profile. Function results include complete observed body ranges, distinguishing owned bytes from the enclosing span. See the [DOS analysis guide](docs/ghidra-dos.md) for addresses, packing, and verification boundaries.
Windows operations remain unavailable pending the controls described in the [Windows Ghidra P0 guide](docs/windows-ghidra-p0.md). See [Ghidra installation](docs/installation.md#ghidra), [provider evaluation](docs/provider-evaluation.md), and [testing](docs/testing.md) for configuration details, coverage, and real-provider verification.
Windows Ghidra P0 uses bundled native controls for its read-only native x86-64 PE boundary on local NTFS; see the [Windows Ghidra P0 guide](docs/windows-ghidra-p0.md). See [Ghidra installation](docs/installation.md#ghidra), [provider evaluation](docs/provider-evaluation.md), and [testing](docs/testing.md) for configuration details, coverage, and real-provider verification.
To remove only REA-owned MCP registrations and the managed skill:
@@ -305,7 +307,7 @@ See [native investigation](docs/native-investigation.md) for keyed archives, ins
| Tool family | Count | Examples |
| ------------------------- | ----: | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Native inspection | 39 | functions, pseudocode, assembly, strings, symbols, calls, references, annotations, byte reads, and file offsets |
| Native inspection | 41 | functions, pseudocode, assembly, strings, symbols, calls, references, annotations, byte reads, and file offsets |
| Investigation workflows | 14 | app overviews, function dossiers, native APIs and dispatch, batch decompilation, feature traces, call paths, call graphs, Swift and Objective-C discovery |
| Native macOS utilities | 7 | Mach-O metadata, code signatures, plists, architectures, and Swift demangling without launching Hopper |
| Artifact graph | 5 | directory and package inventories, compiled Interface Builder files, Apple asset catalogs, and extraction |
@@ -333,7 +335,7 @@ REA supports native application, JavaScript, Electron, .NET, and browser investi
- **Open questions:** Track unresolved findings, contradictions, and follow-up probes. Reconstruction checks report pass, fail, or unknown rather than treating missing evidence as a pass.
- **Guided workflows:** Start six [MCP investigation workflows](docs/mcp-prompts.md) with suggestions based on your current session.
Windows Ghidra operations are currently unavailable. Hopper-only features, such as GUI controls and annotations, are not available through Ghidra.
Windows Ghidra P0 supports the read-only native x86-64 PE boundary on local NTFS. Hopper-only features, such as GUI controls and annotations, are not available through Ghidra.
### Website observation with CDP
@@ -382,7 +384,7 @@ relationships, event activity, IPC, process identity, or Electron roles. See
[Node and Electron runtime observation](docs/javascript-runtime-observation.md)
for the exact coverage.
Exact package, tool-family, provider, setup-client, schema, and CLI facts are generated from source in [`docs/product-catalog.json`](docs/product-catalog.json). PR CI verifies this catalog, narrative documentation, generated schemas, and a clean TypeDoc render.
Exact package, tool-family, provider, setup-client, schema, and CLI facts are generated from source in [`docs/product-catalog.json`](docs/product-catalog.json). PR CI verifies this catalog, narrative documentation, and generated schemas.
## Roadmap
@@ -451,7 +453,7 @@ flowchart LR
REA --> Session["Target-bound session router"]
Session --> Registry["Deep-provider registry<br/>deterministic selection"]
Registry --> Hopper["Hopper provider"]
Registry --> Ghidra["Ghidra provider<br/>read-only inventory + function analysis"]
Registry --> Ghidra["Ghidra provider<br/>inventory + function analysis + annotations"]
Hopper --> Runtime["Owned provider runtime<br/>deadline + bounded diagnostics + cleanup"]
Ghidra --> Runtime
Session --> Native["Native macOS provider"]
@@ -520,7 +522,7 @@ Use `--provider`, or `provider_id` in MCP, to choose Hopper or Ghidra for a targ
With `auto`, REA selects the only available tool that supports the target. If both are available, specify one before opening the target. The session keeps that choice until you explicitly switch or close it; a failure never silently switches tools. Artifact-only analysis can work without a native analysis tool.
Run `rea providers` and `rea capabilities` to check availability and supported operations. Ghidra exposes 22 read-only operations on supported Linux and macOS hosts. GUI controls and annotation changes require Hopper. Windows Ghidra operations remain unavailable.
Run `rea providers` and `rea capabilities` to check availability and supported operations. Ghidra supports inspection and atomic function annotation edits on Linux and macOS. Its database edits are discarded on close; GUI controls require Hopper. Windows Ghidra P0 supports read-only analysis of native x86-64 PE applications on local NTFS with bundled native controls.
The session also reports active work and cleanup status. If a caller times out, the analysis tool may still be busy; `analysis_activity` reports that state. A `cleanup_incomplete` result identifies resources whose shutdown or removal could not be verified. See [provider selection and analysis profiles](docs/adr/0001-provider-selection-and-analysis-profiles.md) for session, cache, and process-tracking details.
@@ -532,7 +534,9 @@ The session also reports active work and cleanup status. If a caller times out,
| `1` | The operation could not complete, for example because of invalid input, host permission denial, cancellation, or timeout. Structured output reports the reason when available. |
| `128 + N` | The process ended from signal `N`, where the shell or runtime preserves the conventional signal-derived status. |
`setup` returns `1` for `planned`, `needs_confirmation`, or `needs_human`
`setup --dry-run` returns status `planned` and exits `0`. A setup result with
status `cancelled` also exits `0`.
`setup` returns `1` for `needs_confirmation` or `needs_human`
because configuration is not ready; rerun it after approval or remediation.
`doctor` returns `1` when required checks for its readiness scope are unhealthy.
Unavailable optional provider prerequisites remain visible as informational
@@ -544,7 +548,7 @@ cannot hide its failure:
```bash
set -o pipefail
rea inventory-artifact ./app.asar --json | jq . > inventory.json
rea inspect-artifact ./app.asar --json | jq . > inspection.json
```
## Current Hopper provider
@@ -596,7 +600,7 @@ Analysis runs locally. REA communicates with Hopper and Ghidra through authentic
Runtime requests act on the declared target and lifecycle. Analysis tools and launched targets run with your user permissions, and native UI capture still depends on macOS Accessibility and Screen Recording access. Static JavaScript analysis does not execute extracted modules; use direct browser, Electron, or process capture when runtime behavior is needed.
Windows Ghidra operations are blocked until REA implements the required process ownership, private-directory permissions, and safe-path checks. Report vulnerabilities through the private process in [SECURITY.md](SECURITY.md).
Windows Ghidra P0 automatically uses native Job Objects, protected private-runtime DACLs, and handle-based admission. Its experimental scope is native x86-64 PE applications on local NTFS. Report vulnerabilities through the private process in [SECURITY.md](SECURITY.md).
## FAQ
@@ -624,7 +628,7 @@ No. Setup can install Hopper for you, but Hopper remains separate software with
<details>
<summary><strong>Does REA install or include Ghidra or Java?</strong></summary>
No. REA connects to an existing Ghidra installation. Run setup after providing the Ghidra and Java paths shown in the [Ghidra section](#ghidra-read-only-analysis-provider).
No. REA connects to an existing Ghidra installation. Run setup after providing the Ghidra and Java paths shown in the [Ghidra section](#ghidra-analysis-provider).
</details>
@@ -651,7 +655,7 @@ Any agent that can run a local MCP server can use the manual configuration. Setu
## Development
See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup and contribution checks, and [docs/testing.md](docs/testing.md) for test scopes and real-tool verification. PR CI publishes generated API documentation as the `api-docs` artifact.
See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup and contribution checks, and [docs/testing.md](docs/testing.md) for test scopes and real-tool verification. `npm run docs:check` checks committed generated documents; `npm run docs:generate` regenerates them.
`npm run verify:agent` evaluates native, JavaScript, managed, and browser investigation tasks through a real local Codex CLI. Its report covers tool selection, repeated calls, token use, completion quality, and handling of permissions and unknowns.
+6 -4
View File
@@ -15,6 +15,8 @@
[![MIT license](https://img.shields.io/badge/license-MIT-f4c430?style=flat-square)](LICENSE)
[![Discord](https://img.shields.io/discord/1556595354999332884?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/GkcryMnJDM)
<a href="https://trendshift.io/repositories/82054?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-82054" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/82054/weekly?language=TypeScript" alt="morluto/rea | Trendshift" width="250" height="55" /></a>
[البدء السريع](#البدء-السريع) · [حالة الدعم](#حالة-الدعم) · [من الملف التنفيذي إلى السلوك](#من-الملف-التنفيذي-إلى-السلوك) · [منصة أدوات التحقيق](#منصة-أدوات-التحقيق) · [خطة العمل](#خطة-العمل) · [كيف يعمل؟](#كيف-يعمل)
<table aria-label="REA community">
@@ -92,7 +94,7 @@ npx rea-agents setup
### الاستخدام مع وكيل
بعد الإعداد، أعد تشغيل الوكيل واشرح التطبيق أو الميزة التي تريد استقصاءها. يدعم REA Claude Code وClaude Desktop وCodex وCursor وGemini CLI وWindsurf وDevin وOpenCode وAntigravity وGitHub Copilot CLI وVS Code. تكون تسجيلات REA الموجودة محددة افتراضياً، ويجب اختيار العملاء المكتشفين الآخرين يدوياً. يمكن للوكلاء الآخرين استخدام إعداد MCP أدناه.
بعد الإعداد، أعد تشغيل الوكيل واشرح التطبيق أو الميزة التي تريد استقصاءها. يدعم REA Claude Code وClaude Desktop وCodex وCursor وGemini CLI وWindsurf وDevin وOpenCode وAntigravity وGitHub Copilot CLI وCommand Code وVS Code. تكون تسجيلات REA الموجودة محددة افتراضياً، ويجب اختيار العملاء المكتشفين الآخرين يدوياً. يمكن للوكلاء الآخرين استخدام إعداد MCP أدناه.
يمكن تشغيل Hopper في الوضع التجريبي. إذا ظهرت رسالة عند التشغيل الأول، فاختر التجربة أو أدخل ترخيصًا موجودًا.
@@ -126,7 +128,7 @@ rea setup
- macOS 12 أو أحدث
- Ubuntu 24.04+ أو Fedora 41+ أو Arch Linux بنواة 64 بت
- Node.js 22.19+ أو 24.11+ وnpm
- Node.js 22.x (>=22.19) أو 24.x (>=24.11) أو 26+ وnpm
يتطلب تحليل الملفات التنفيذية الأصلية Hopper أو Ghidra. Hopper برنامج منفصل، وللوضع التجريبي قيود يحددها المورّد، لكن الترخيص المدفوع ليس إلزاميًا.
@@ -202,7 +204,7 @@ rea setup
| عائلة الأدوات | العدد | الاستخدام |
| --------------------- | ----: | -------------------------------------------------------------------------------------- |
| فحص الملفات التنفيذية | 39 | الدوال والشيفرة شبه المصدرية والتعليمات والسلاسل والرموز والمراجع والتعليقات |
| فحص الملفات التنفيذية | 41 | الدوال والشيفرة شبه المصدرية والتعليمات والسلاسل والرموز والمراجع والتعليقات |
| التحليل المركب | 14 | النظرة العامة وتحليل الدوال وفك الترجمة الدفعي ومخطط الاستدعاء وفحص Swift وObjC |
| أدوات macOS الأصلية | 7 | بيانات Mach-O والتوقيعات وplist والمعماريات واستعادة أسماء Swift |
| الملفات والحزم | 5 | فحص الدلائل والحزم وInterface Builder وموارد Apple والاستخراج |
@@ -219,7 +221,7 @@ rea setup
## استخدام REA مع وكلاء برمجة آخرين
يدعم Setup Claude Code وClaude Desktop وCodex وCursor وGemini CLI وWindsurf وDevin وOpenCode وAntigravity وGitHub Copilot CLI وVS Code. تكون تسجيلات REA الموجودة محددة افتراضياً، ويجب اختيار العملاء المكتشفين الآخرين يدوياً. يمكن لأي وكيل يدعم خوادم MCP المحلية الاتصال باستخدام الإعداد التالي:
يدعم Setup Claude Code وClaude Desktop وCodex وCursor وGemini CLI وWindsurf وDevin وOpenCode وAntigravity وGitHub Copilot CLI وCommand Code وVS Code. تكون تسجيلات REA الموجودة محددة افتراضياً، ويجب اختيار العملاء المكتشفين الآخرين يدوياً. يمكن لأي وكيل يدعم خوادم MCP المحلية الاتصال باستخدام الإعداد التالي:
<!-- x-release-please-start-version -->
+6 -4
View File
@@ -15,6 +15,8 @@
[![MIT license](https://img.shields.io/badge/license-MIT-f4c430?style=flat-square)](LICENSE)
[![Discord](https://img.shields.io/discord/1556595354999332884?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/GkcryMnJDM)
<a href="https://trendshift.io/repositories/82054?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-82054" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/82054/weekly?language=TypeScript" alt="morluto/rea | Trendshift" width="250" height="55" /></a>
[クイックスタート](#クイックスタート) · [現在の対応状況](#現在の対応状況) · [バイナリから動作へ](#バイナリから動作へ) · [調査ツールカタログ](#調査ツールカタログ) · [ロードマップ](#ロードマップ) · [仕組み](#仕組み)
<table aria-label="REA community">
@@ -92,7 +94,7 @@ Setup は最初に連携するエージェントを複数選択できるよう
### エージェントで使う
設定後にエージェントを再起動し、調べたいアプリや機能を説明します。REA は Claude Code、Claude Desktop、Codex、Cursor、Gemini CLI、Windsurf、Devin、OpenCode、Antigravity、GitHub Copilot CLI、VS Code に対応します。既存の REA 登録は初期選択され、それ以外の検出済みクライアントは選択が必要です。その他のエージェントは下記の MCP 設定を使えます。
設定後にエージェントを再起動し、調べたいアプリや機能を説明します。REA は Claude Code、Claude Desktop、Codex、Cursor、Gemini CLI、Windsurf、Devin、OpenCode、Antigravity、GitHub Copilot CLI、Command Code、VS Code に対応します。既存の REA 登録は初期選択され、それ以外の検出済みクライアントは選択が必要です。その他のエージェントは下記の MCP 設定を使えます。
Hopper はデモモードで使えます。初回起動の画面ではデモを選択するか、既存のライセンスを入力してください。
@@ -126,7 +128,7 @@ rea setup
- macOS 12 以降
- Ubuntu 24.04+、Fedora 41+、または 64 ビット Arch Linux
- Node.js 22.19+ または 24.11+ と npm
- Node.js 22.x (>=22.19)、24.x (>=24.11)、または 26+ と npm
ネイティブバイナリ解析には Hopper または Ghidra が必要です。Hopper は別製品です。デモにはベンダー所定の制限がありますが、有料ライセンスは必須ではありません。
@@ -191,7 +193,7 @@ REA は手順 1〜5 のバイナリ解析を処理し、手順 6 はエージェ
| ツール分類 | 数 | 用途 |
| -------------------- | --: | --------------------------------------------------------------------------- |
| バイナリ検査 | 39 | 関数、疑似コード、アセンブリ、文字列、シンボル、参照、注釈 |
| バイナリ検査 | 41 | 関数、疑似コード、アセンブリ、文字列、シンボル、参照、注釈 |
| 組み合わせた解析 | 14 | 概要、関数解析、一括逆コンパイル、呼び出しグラフ、Swift と ObjC |
| macOS ネイティブ | 7 | Mach-O メタデータ、署名、plist、アーキテクチャ、Swift 名の復元 |
| ファイルとパッケージ | 5 | ディレクトリとパッケージ、Interface Builder、Apple リソース、抽出 |
@@ -208,7 +210,7 @@ REA は手順 1〜5 のバイナリ解析を処理し、手順 6 はエージェ
## 他のコーディングエージェントで使う
Setup は Claude Code、Claude Desktop、Codex、Cursor、Gemini CLI、Windsurf、Devin、OpenCode、Antigravity、GitHub Copilot CLI、VS Code に対応します。既存の REA 登録は初期選択され、それ以外の検出済みクライアントは選択が必要です。ローカル MCP サーバーに対応するエージェントは、次の設定でも接続できます。
Setup は Claude Code、Claude Desktop、Codex、Cursor、Gemini CLI、Windsurf、Devin、OpenCode、Antigravity、GitHub Copilot CLI、Command Code、VS Code に対応します。既存の REA 登録は初期選択され、それ以外の検出済みクライアントは選択が必要です。ローカル MCP サーバーに対応するエージェントは、次の設定でも接続できます。
<!-- x-release-please-start-version -->
+6 -4
View File
@@ -15,6 +15,8 @@
[![MIT license](https://img.shields.io/badge/license-MIT-f4c430?style=flat-square)](LICENSE)
[![Discord](https://img.shields.io/discord/1556595354999332884?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/GkcryMnJDM)
<a href="https://trendshift.io/repositories/82054?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-82054" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/82054/weekly?language=TypeScript" alt="morluto/rea | Trendshift" width="250" height="55" /></a>
[빠른 시작](#빠른-시작) · [현재 지원 범위](#현재-지원-범위) · [바이너리에서 동작까지](#바이너리에서-동작까지) · [조사 도구 카탈로그](#조사-도구-카탈로그) · [로드맵](#로드맵) · [작동 방식](#작동-방식)
<table aria-label="REA community">
@@ -93,7 +95,7 @@ Setup은 먼저 연결할 에이전트를 여러 개 선택하도록 안내합
### 에이전트에서 사용하기
설정 후 에이전트를 다시 시작하고 조사할 앱이나 기능을 설명하세요. REA는 Claude Code, Claude Desktop, Codex, Cursor, Gemini CLI, Windsurf, Devin, OpenCode, Antigravity, GitHub Copilot CLI, VS Code를 지원합니다. 기존 REA 등록은 기본 선택되고, 그 밖의 감지된 클라이언트는 직접 선택해야 합니다. 다른 에이전트는 아래 MCP 설정을 사용할 수 있습니다.
설정 후 에이전트를 다시 시작하고 조사할 앱이나 기능을 설명하세요. REA는 Claude Code, Claude Desktop, Codex, Cursor, Gemini CLI, Windsurf, Devin, OpenCode, Antigravity, GitHub Copilot CLI, Command Code, VS Code를 지원합니다. 기존 REA 등록은 기본 선택되고, 그 밖의 감지된 클라이언트는 직접 선택해야 합니다. 다른 에이전트는 아래 MCP 설정을 사용할 수 있습니다.
Hopper는 데모 모드로 사용할 수 있습니다. 첫 실행 안내가 나오면 데모를 선택하거나 기존 라이선스를 입력하세요.
@@ -127,7 +129,7 @@ rea setup
- macOS 12 이상
- Ubuntu 24.04+, Fedora 41+ 또는 64비트 Arch Linux
- Node.js 22.19+ 또는 24.11+와 npm
- Node.js 22.x (>=22.19), 24.x (>=24.11) 또는 26+와 npm
네이티브 바이너리 분석에는 Hopper 또는 Ghidra가 필요합니다. Hopper는 별도 소프트웨어입니다. 데모에는 공급업체의 제한이 있지만 유료 라이선스가 필수는 아닙니다.
@@ -192,7 +194,7 @@ REA는 1–5단계의 바이너리 분석을 처리합니다. 6단계는 에이
| 도구 분류 | 수 | 용도 |
| ----------------- | --: | -------------------------------------------------------------------- |
| 바이너리 검사 | 39 | 함수, 의사 코드, 어셈블리, 문자열, 심볼, 참조, 주석 |
| 바이너리 검사 | 41 | 함수, 의사 코드, 어셈블리, 문자열, 심볼, 참조, 주석 |
| 결합 분석 | 14 | 개요, 함수 분석, 일괄 디컴파일, 호출 그래프, Swift와 ObjC 검사 |
| macOS 네이티브 | 7 | Mach-O 메타데이터, 서명, plist, 아키텍처, Swift 이름 복원 |
| 파일과 패키지 | 5 | 디렉터리와 패키지 검사, Interface Builder, Apple 리소스, 추출 |
@@ -209,7 +211,7 @@ REA는 1–5단계의 바이너리 분석을 처리합니다. 6단계는 에이
## 다른 코딩 에이전트에서 사용하기
Setup은 Claude Code, Claude Desktop, Codex, Cursor, Gemini CLI, Windsurf, Devin, OpenCode, Antigravity, GitHub Copilot CLI, VS Code를 지원합니다. 기존 REA 등록은 기본 선택되고, 그 밖의 감지된 클라이언트는 직접 선택해야 합니다. 로컬 MCP 서버를 지원하는 에이전트는 다음 설정으로 연결할 수 있습니다.
Setup은 Claude Code, Claude Desktop, Codex, Cursor, Gemini CLI, Windsurf, Devin, OpenCode, Antigravity, GitHub Copilot CLI, Command Code, VS Code를 지원합니다. 기존 REA 등록은 기본 선택되고, 그 밖의 감지된 클라이언트는 직접 선택해야 합니다. 로컬 MCP 서버를 지원하는 에이전트는 다음 설정으로 연결할 수 있습니다.
<!-- x-release-please-start-version -->
+6 -4
View File
@@ -15,6 +15,8 @@
[![MIT license](https://img.shields.io/badge/license-MIT-f4c430?style=flat-square)](LICENSE)
[![Discord](https://img.shields.io/discord/1556595354999332884?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/GkcryMnJDM)
<a href="https://trendshift.io/repositories/82054?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-82054" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/82054/weekly?language=TypeScript" alt="morluto/rea | Trendshift" width="250" height="55" /></a>
[快速开始](#快速开始) · [当前状态](#当前状态) · [从二进制到行为](#从二进制到行为) · [调查工具目录](#调查工具目录) · [路线图](#路线图) · [工作原理](#工作原理)
<table aria-label="REA community">
@@ -92,7 +94,7 @@ Setup 会先展示变更并备份已有配置。要求与更多选项见[安装
### 使用智能体
设置完成后,重启智能体并描述你想了解的应用或功能。REA 支持 Claude Code、Claude Desktop、Codex、Cursor、Gemini CLI、Windsurf、Devin、OpenCode、Antigravity、GitHub Copilot CLI 和 VS Code。已有 REA 注册默认选中;其他检测到的客户端需手动选择。其他智能体可以使用下方的 MCP 配置。
设置完成后,重启智能体并描述你想了解的应用或功能。REA 支持 Claude Code、Claude Desktop、Codex、Cursor、Gemini CLI、Windsurf、Devin、OpenCode、Antigravity、GitHub Copilot CLI、Command Code 和 VS Code。已有 REA 注册默认选中;其他检测到的客户端需手动选择。其他智能体可以使用下方的 MCP 配置。
Hopper 支持演示模式。如果首次启动时出现提示,选择演示模式或输入已有许可证。
@@ -126,7 +128,7 @@ rea setup
- macOS 12 或更高版本
- Ubuntu 24.04+、Fedora 41+ 或 64 位 Arch Linux
- Node.js 22.19+ 或 24.11+,以及 npm
- Node.js 22.x (>=22.19)、24.x (>=24.11) 或 26+,以及 npm
原生二进制分析需要 Hopper 或 Ghidra。Hopper 是独立软件;演示模式有厂商规定的限制,不要求购买许可证。
@@ -191,7 +193,7 @@ REA 负责第 1–5 步中的二进制分析。第 6 步由智能体使用其常
| 工具类别 | 数量 | 用途 |
| ----------------- | ---: | --------------------------------------------------------- |
| 二进制检查 | 39 | 函数、伪代码、汇编、字符串、符号、段、引用与注释 |
| 二进制检查 | 41 | 函数、伪代码、汇编、字符串、符号、段、引用与注释 |
| 组合分析 | 14 | 概览、函数分析、批量反编译、调用图、Swift 与 ObjC 检查 |
| macOS 原生工具 | 7 | Mach-O 元数据、代码签名、plist、架构与 Swift 符号还原 |
| 制品检查 | 5 | 目录与软件包检查、Interface Builder、Apple 资源目录与提取 |
@@ -208,7 +210,7 @@ REA 负责第 1–5 步中的二进制分析。第 6 步由智能体使用其常
## 与其他编程智能体一起使用
Setup 支持 Claude Code、Claude Desktop、Codex、Cursor、Gemini CLI、Windsurf、Devin、OpenCode、Antigravity、GitHub Copilot CLI 和 VS Code。已有 REA 注册默认选中;其他检测到的客户端需手动选择。任何支持本地 MCP 服务器的智能体都可以使用以下配置连接 REA。
Setup 支持 Claude Code、Claude Desktop、Codex、Cursor、Gemini CLI、Windsurf、Devin、OpenCode、Antigravity、GitHub Copilot CLI、Command Code 和 VS Code。已有 REA 注册默认选中;其他检测到的客户端需手动选择。任何支持本地 MCP 服务器的智能体都可以使用以下配置连接 REA。
<!-- x-release-please-start-version -->
+336 -9
View File
@@ -73,6 +73,11 @@ import ghidra.program.model.listing.Instruction;
import ghidra.program.model.listing.InstructionIterator;
import ghidra.program.model.listing.Variable;
import ghidra.program.model.mem.MemoryBlock;
import ghidra.program.model.mem.MemoryBlockSourceInfo;
import ghidra.program.database.mem.FileBytes;
import ghidra.program.model.address.SegmentedAddress;
import ghidra.program.model.reloc.Relocation;
import java.io.ByteArrayOutputStream;
import ghidra.program.model.symbol.RefType;
import ghidra.program.model.symbol.Reference;
import ghidra.program.model.symbol.ReferenceIterator;
@@ -112,6 +117,10 @@ public final class ReaGhidraBridge extends HeadlessScript {
"params"
);
private static final String[] CAPABILITIES = {
"annotate_native_function",
"inspect_native_load_image",
"read_bytes",
"address_to_file_offset",
"ping",
"shutdown",
"address_name",
@@ -152,12 +161,24 @@ public final class ReaGhidraBridge extends HeadlessScript {
}
Path descriptorPath = Path.of(arguments[0]);
SessionDescriptor descriptor = readDescriptor(descriptorPath);
Files.deleteIfExists(descriptorPath);
// Windows retains a native immutable bearer descriptor lease until
// runtime_close; POSIX removes it after this read. Normal cleanup removes
// the Windows file, while abrupt owner death can leave private residue.
// Its protected runtime DACL also protects the bearer token while the
// bridge is running. POSIX keeps its existing consume-and-delete flow.
if (!isWindowsHost()) {
Files.deleteIfExists(descriptorPath);
}
if (currentProgram == null) {
throw new IllegalStateException("REA bridge requires an imported program");
}
sessionDefaultAddressSpace =
currentProgram.getAddressFactory().getDefaultAddressSpace();
if (currentProgram.getExecutableFormat().equals("Raw Binary") &&
!currentProgram.getOptions(ghidra.program.model.listing.Program.PROGRAM_INFO)
.getBoolean("REA DOS COM prepared", false)) {
throw new IllegalStateException("REA DOS COM entry/context preparation failed");
}
if (!Application.getApplicationVersion().equals(descriptor.providerVersion)) {
throw new IllegalStateException("Ghidra provider version does not match the session");
}
@@ -171,6 +192,9 @@ public final class ReaGhidraBridge extends HeadlessScript {
"Ghidra imported-byte digest does not match the admitted target"
);
}
// GhidraScript wraps run() in a transaction. End it before serving so
// each edit owns a real outer transaction and can roll back immediately.
end(true);
try {
initializeDecompiler();
serve(descriptor);
@@ -219,18 +243,23 @@ public final class ReaGhidraBridge extends HeadlessScript {
JsonObject endpoint = new JsonObject();
endpoint.addProperty("host", "127.0.0.1");
endpoint.addProperty("port", address.getPort());
// The Windows native reader refuses a file while a writer still
// owns it. Closing CREATE_NEW publishes the complete record without
// requesting rename rights on the retained private directory guard.
Files.writeString(
pendingPath,
isWindowsHost() ? endpointPath : pendingPath,
GSON.toJson(endpoint) + "\n",
StandardCharsets.UTF_8,
StandardOpenOption.CREATE_NEW,
StandardOpenOption.WRITE
);
try {
Files.move(pendingPath, endpointPath, StandardCopyOption.ATOMIC_MOVE);
}
catch (AtomicMoveNotSupportedException exception) {
Files.move(pendingPath, endpointPath);
if (!isWindowsHost()) {
try {
Files.move(pendingPath, endpointPath, StandardCopyOption.ATOMIC_MOVE);
}
catch (AtomicMoveNotSupportedException exception) {
Files.move(pendingPath, endpointPath);
}
}
acceptClient(server, descriptor);
}
@@ -240,6 +269,10 @@ public final class ReaGhidraBridge extends HeadlessScript {
}
}
private static boolean isWindowsHost() {
return System.getProperty("os.name", "").startsWith("Windows");
}
private void acceptClient(
ServerSocketChannel server,
SessionDescriptor descriptor) throws Exception {
@@ -309,6 +342,9 @@ public final class ReaGhidraBridge extends HeadlessScript {
);
}
return switch (request.method) {
case "inspect_native_load_image" -> inspectNativeLoadImage(request.params);
case "read_bytes" -> readMemoryBytes(request.params);
case "address_to_file_offset" -> addressToFileOffset(request.params);
case "address_name" -> addressName(request.params);
case "list_documents" -> listDocuments(request.params);
case "list_names" -> listNames(request.params);
@@ -331,6 +367,11 @@ public final class ReaGhidraBridge extends HeadlessScript {
case "resolve_native_call_targets" -> resolveNativeCallTargets(request.params);
case "xrefs" -> xrefs(request.params);
case "analyze_function" -> analyzeFunction(request.params);
case "annotate_native_function" -> {
if (!descriptor.transport.equals("unix-socket"))
throw new RequestFailure("method_unavailable", "Windows P0 does not admit database mutation");
yield annotateNativeFunction(request.params);
}
default -> throw new RequestFailure(
"method_unavailable",
"Bridge method is unavailable"
@@ -363,14 +404,216 @@ public final class ReaGhidraBridge extends HeadlessScript {
result.addProperty("run_id", descriptor.runId);
result.addProperty("profile_digest", descriptor.profileDigest);
result.add("provider", provider);
result.addProperty("read_only", true);
boolean readOnly = !descriptor.transport.equals("unix-socket");
result.addProperty("read_only", readOnly);
result.addProperty("analysis_complete", !timedOut);
result.addProperty("analysis_timed_out", timedOut);
result.add("capabilities", GSON.toJsonTree(CAPABILITIES));
result.add("capabilities", GSON.toJsonTree(
java.util.Arrays.stream(CAPABILITIES)
.filter(value -> !readOnly || !value.equals("annotate_native_function"))
.toArray(String[]::new)
));
result.add("target", target);
return result;
}
private static String bytesHex(byte[] bytes) {
return java.util.HexFormat.of().formatHex(bytes);
}
private String hashFileBytes(FileBytes source, boolean modified) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] chunk = new byte[65536];
for (long offset = 0; offset < source.getSize();) {
monitor.checkCancelled();
int length = (int) Math.min(chunk.length, source.getSize() - offset);
int read = modified
? source.getModifiedBytes(offset, chunk, 0, length)
: source.getOriginalBytes(offset, chunk, 0, length);
if (read != length) throw new IOException("Incomplete FileBytes read at " + offset);
digest.update(chunk, 0, read);
offset += read;
}
return bytesHex(digest.digest());
}
private String hashMemory(Address start, long length) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] chunk = new byte[65536];
for (long offset = 0; offset < length;) {
monitor.checkCancelled();
int count = (int) Math.min(chunk.length, length - offset);
int read = currentProgram.getMemory().getBytes(start.add(offset), chunk, 0, count);
if (read != count) throw new IOException("Incomplete memory read at " + start.add(offset));
digest.update(chunk, 0, read);
offset += read;
}
return bytesHex(digest.digest());
}
private JsonObject inspectNativeLoadImage(JsonObject params) throws Exception {
requireKeys(params, Set.of());
JsonObject result = new JsonObject();
result.addProperty("executable_format", currentProgram.getExecutableFormat());
result.addProperty("language_id", currentProgram.getLanguageID().getIdAsString());
result.addProperty("compiler_spec_id", currentProgram.getCompilerSpec().getCompilerSpecID().getIdAsString());
result.addProperty("image_base", canonicalAddress(currentProgram.getImageBase()));
result.addProperty("default_address_space", sessionDefaultAddressSpace.getName());
List<FileBytes> files = currentProgram.getMemory().getAllFileBytes();
JsonArray sources = new JsonArray();
for (FileBytes file : files) {
JsonObject source = new JsonObject();
source.addProperty("name", file.getFilename());
source.addProperty("size", file.getSize());
source.addProperty("original_sha256", hashFileBytes(file, false));
source.addProperty("modified_sha256", hashFileBytes(file, true));
sources.add(source);
}
result.add("source_files", sources);
JsonArray mappings = new JsonArray();
for (MemoryBlock block : currentProgram.getMemory().getBlocks()) {
for (MemoryBlockSourceInfo source : block.getSourceInfos()) {
monitor.checkCancelled();
JsonObject mapping = new JsonObject();
mapping.addProperty("block", block.getName());
mapping.addProperty("start", canonicalAddress(source.getMinAddress()));
mapping.addProperty("end", canonicalAddress(source.getMaxAddress()));
mapping.addProperty("address_space", source.getMinAddress().getAddressSpace().getName());
mapping.addProperty("initialized", block.isInitialized());
mapping.addProperty("loaded", block.isLoaded());
mapping.addProperty("overlay", block.isOverlay());
mapping.addProperty("length", source.getLength());
FileBytes backing = source.getFileBytes().orElse(null);
int sourceIndex = backing == null ? -1 : files.indexOf(backing);
if (sourceIndex < 0) mapping.add("source_file_index", JsonNull.INSTANCE);
else mapping.addProperty("source_file_index", sourceIndex);
long offset = source.getFileBytesOffset();
if (offset < 0) mapping.add("file_offset", JsonNull.INSTANCE);
else mapping.addProperty("file_offset", offset);
if (block.isInitialized()) mapping.addProperty("sha256", hashMemory(source.getMinAddress(), source.getLength()));
else mapping.add("sha256", JsonNull.INSTANCE);
mappings.add(mapping);
}
}
result.add("mappings", mappings);
JsonArray relocations = new JsonArray();
Iterator<Relocation> iterator = currentProgram.getRelocationTable().getRelocations();
while (iterator.hasNext()) {
monitor.checkCancelled();
Relocation relocation = iterator.next();
Address location = relocation.getAddress();
JsonObject row = new JsonObject();
row.addProperty("address", canonicalAddress(location));
if (location instanceof SegmentedAddress segmented) {
row.addProperty("segment", segmented.getSegment());
row.addProperty("offset", segmented.getSegmentOffset());
} else {
row.add("segment", JsonNull.INSTANCE);
row.add("offset", JsonNull.INSTANCE);
}
row.addProperty("status", relocation.getStatus().toString());
row.addProperty("type", relocation.getType());
row.add("values", GSON.toJsonTree(relocation.getValues() == null ? new long[0] : relocation.getValues()));
byte[] original = relocation.getBytes();
row.add("original_bytes_hex", original == null ? JsonNull.INSTANCE : GSON.toJsonTree(bytesHex(original)));
if (original != null && original.length > 0) {
byte[] memory = new byte[original.length];
int read = currentProgram.getMemory().getBytes(location, memory);
row.add("memory_bytes_hex", read == memory.length ? GSON.toJsonTree(bytesHex(memory)) : JsonNull.INSTANCE);
} else row.add("memory_bytes_hex", JsonNull.INSTANCE);
relocations.add(row);
}
result.add("relocations", relocations);
List<Address> entries = new ArrayList<>();
var entryIterator = currentProgram.getSymbolTable().getExternalEntryPointIterator();
while (entryIterator.hasNext()) entries.add(entryIterator.next());
entries.sort(Address::compareTo);
JsonArray entryPoints = new JsonArray();
for (Address entry : entries) entryPoints.add(canonicalAddress(entry));
result.add("entry_points", entryPoints);
JsonArray contexts = new JsonArray();
for (Address entry : entries) {
JsonObject context = new JsonObject();
context.addProperty("address", canonicalAddress(entry));
JsonArray registers = new JsonArray();
for (String name : new String[] { "CS", "DS", "ES", "SS" }) {
Register register = currentProgram.getRegister(name);
if (register == null) continue;
JsonObject row = new JsonObject();
row.addProperty("name", name);
BigInteger value = currentProgram.getProgramContext().getValue(register, entry, false);
row.add("value_hex", value == null ? JsonNull.INSTANCE : GSON.toJsonTree("0x" + value.toString(16)));
registers.add(row);
}
context.add("registers", registers);
contexts.add(context);
}
result.add("entry_context", contexts);
return result;
}
private JsonObject readMemoryBytes(JsonObject params) throws Exception {
requireKeys(params, Set.of("document", "address", "length"));
requireDocument(params);
Address start = requireAddress(params, "address");
JsonElement requested = params.get("length");
long length;
try {
if (requested == null || !requested.isJsonPrimitive() || !requested.getAsJsonPrimitive().isNumber())
throw new IllegalArgumentException();
length = requested.getAsBigDecimal().longValueExact();
if (length < 1 || length > 9007199254740991L) throw new IllegalArgumentException();
} catch (RuntimeException failure) {
throw new RequestFailure("invalid_request", "Byte length must be a positive safe integer");
}
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
byte[] chunk = new byte[65536];
for (long offset = 0; offset < length;) {
monitor.checkCancelled();
Address at;
try { at = start.addNoWrap(offset); }
catch (Exception endOfSpace) { break; }
MemoryBlock block = currentProgram.getMemory().getBlock(at);
if (block == null || !block.isInitialized()) break;
int count = (int) Math.min(chunk.length, Math.min(length - offset, block.getEnd().subtract(at) + 1));
int read = currentProgram.getMemory().getBytes(at, chunk, 0, count);
bytes.write(chunk, 0, read);
if (read != count) break;
offset += read;
}
JsonObject result = new JsonObject();
result.addProperty("address", canonicalAddress(start));
result.addProperty("requested_bytes", length);
result.addProperty("returned_bytes", bytes.size());
result.addProperty("bytes_hex", bytesHex(bytes.toByteArray()));
result.addProperty("complete", bytes.size() == length);
return result;
}
private JsonObject addressToFileOffset(JsonObject params) {
requireKeys(params, Set.of("document", "address"));
requireDocument(params);
Address address = requireAddress(params, "address");
MemoryBlock block = currentProgram.getMemory().getBlock(address);
if (block == null || !block.isInitialized())
throw new RequestFailure("invalid_request", "Address has no initialized file-backed memory: " + canonicalAddress(address));
Long fileOffset = null;
int mappings = 0;
for (MemoryBlockSourceInfo source : block.getSourceInfos()) {
if (!source.contains(address) || source.getFileBytes().isEmpty()) continue;
long offset = source.getFileBytesOffset(address);
if (offset < 0) continue;
fileOffset = offset;
mappings++;
}
if (mappings != 1)
throw new RequestFailure("invalid_request", "Address has " + mappings + " authoritative source mappings: " + canonicalAddress(address));
JsonObject result = new JsonObject();
result.addProperty("address", canonicalAddress(address));
result.addProperty("file_offset", fileOffset);
return result;
}
private void initializeDecompiler() {
DecompileOptions options = new DecompileOptions();
options.setMaxInstructions(Integer.MAX_VALUE);
@@ -725,6 +968,90 @@ public final class ReaGhidraBridge extends HeadlessScript {
return result;
}
private void invalidateAnalysisCaches() {
nameInventory = null;
procedureInventory = null;
stringInventory = null;
if (decompiler != null) decompiler.flushCache();
}
private JsonObject annotationReadback(Function function) {
Address entry = function.getEntryPoint();
JsonObject value = new JsonObject();
value.addProperty("address", canonicalAddress(entry));
value.addProperty("name", procedureName(function));
value.addProperty("comment", currentProgram.getListing().getComment(CommentType.PRE, entry));
value.addProperty("inline_comment", currentProgram.getListing().getComment(CommentType.EOL, entry));
return value;
}
private JsonObject annotateNativeFunction(JsonObject params) throws Exception {
if (!Set.of("procedure", "name", "comment", "inline_comment").containsAll(params.keySet()))
throw new RequestFailure("invalid_request", "Unknown function annotation field");
if (!params.has("name") && !params.has("comment") && !params.has("inline_comment"))
throw new RequestFailure("invalid_request", "Supply at least one annotation change");
Function function = resolveProcedure(requireString(params, "procedure"));
Address entry = function.getEntryPoint();
if (function.isExternal() || !currentProgram.getMemory().contains(entry))
throw new RequestFailure("invalid_request", "Annotations require a local function entry: " + canonicalAddress(entry));
int transaction = currentProgram.startTransaction("REA function annotations");
boolean commit = false;
try {
// Validate edits through Ghidra's own setters, including name rules.
// A later invalid name must roll back earlier comment writes.
for (String field : List.of("comment", "inline_comment")) {
if (params.has(field)) {
String text = requireText(params, field);
CommentType type = field.equals("comment") ? CommentType.PRE : CommentType.EOL;
currentProgram.getListing().setComment(entry, type, text.isEmpty() ? null : text);
}
}
if (params.has("name"))
function.setName(requireString(params, "name"), SourceType.USER_DEFINED);
monitor.checkCancelled();
invalidateAnalysisCaches();
JsonObject readback = annotationReadback(function);
for (String field : List.of("name", "comment", "inline_comment")) {
if (!params.has(field)) continue;
String requested = requireText(params, field);
JsonElement measured = readback.get(field);
String expected = !field.equals("name") && requested.isEmpty() ? null : requested;
String observed = field.equals("name") ? function.getName() :
(measured.isJsonNull() ? null : measured.getAsString());
if (!java.util.Objects.equals(expected, observed))
throw new RequestFailure("annotation_readback_mismatch", "Annotation readback differs for " + field + " at " + canonicalAddress(entry));
}
JsonObject query = new JsonObject();
query.addProperty("procedure", canonicalAddress(entry));
JsonObject result = new JsonObject();
result.add("annotations", readback);
result.add("dossier", analyzeFunction(query));
JsonObject effects = new JsonObject();
effects.addProperty("scope", "session-analysis-database");
effects.addProperty("source_bytes_modified", false);
effects.addProperty("persists_after_close", false);
result.add("effects", effects);
monitor.checkCancelled();
commit = true;
return result;
}
catch (ghidra.util.exception.InvalidInputException | ghidra.util.exception.DuplicateNameException exception) {
throw new RequestFailure("invalid_function_name", "Invalid function name at " + canonicalAddress(entry) + ": " + safeMessage(exception));
}
finally {
currentProgram.endTransaction(transaction, commit);
// Rollback also invalidates inventory and decompiler views.
invalidateAnalysisCaches();
}
}
private static String requireText(JsonObject params, String field) {
JsonElement value = params.get(field);
if (value == null || !value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString())
throw new RequestFailure("invalid_request", "Annotation " + field + " must be text");
return value.getAsString();
}
private JsonObject analyzeFunction(JsonObject params) throws Exception {
requireKeys(params, Set.of("procedure"));
Function function = resolveProcedure(requireString(params, "procedure"));
+32
View File
@@ -0,0 +1,32 @@
import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.Address;
import ghidra.program.model.listing.Program;
import java.math.BigInteger;
/** Seed the declared DOS COM analysis context before default auto-analysis. */
public final class ReaGhidraPrepareCom extends GhidraScript {
@Override
public void run() throws Exception {
if (!currentProgram.getLanguageID().getIdAsString().equals("x86:LE:16:Real Mode") ||
!currentProgram.getExecutableFormat().equals("Raw Binary")) {
throw new IllegalArgumentException("DOS COM preparation requires raw x86 real-mode import");
}
Address entry = currentProgram.getAddressFactory().getDefaultAddressSpace().getAddress("1000:0100");
Address start = currentProgram.getMinAddress();
Address end = currentProgram.getMaxAddress();
if (!entry.equals(start) || end.subtract(start) + 1 > 0xff00) {
throw new IllegalArgumentException("DOS COM import must map 1..65280 bytes at 1000:0100");
}
for (String name : new String[] { "CS", "DS", "ES", "SS" }) {
monitor.checkCancelled();
currentProgram.getProgramContext().setValue(
currentProgram.getRegister(name), start, end, BigInteger.valueOf(0x1000)
);
}
addEntryPoint(entry);
if (!disassemble(entry) || createFunction(entry, "entry") == null) {
throw new IllegalStateException("DOS COM entry cannot be decoded as a function");
}
currentProgram.getOptions(Program.PROGRAM_INFO).setBoolean("REA DOS COM prepared", true);
}
}
@@ -569,5 +569,7 @@ The first six implementation stages are shipped:
Future stages may deepen format and indirect-flow coverage, but must continue
to compare normalized semantics rather than provider-specific pseudocode or
assembly text. Ghidra continues to omit GUI and mutation operations, so
unsupported requests cannot route to an unverified implementation.
assembly text. Linux and macOS now admit atomic function-name and entry-comment
edits in the ephemeral database, with readback, rollback, and cache invalidation.
Executable bytes remain unchanged. Windows P0 retains its read-only boundary;
GUI and other unimplemented mutations remain unavailable.
+5 -5
View File
@@ -4,8 +4,8 @@ Accepted decisions describe the architecture that implementation PRs must
follow. Acceptance does not by itself mean the behavior is shipped; each record
states its implementation status separately.
| ADR | Status | Implementation |
| ------------------------------------------------------------------------------------------------------------------ | -------------------- | -------------------------------------------------------------------------------------------- |
| [0001: Provider selection and analysis profiles](0001-provider-selection-and-analysis-profiles.md) | Accepted | Provider selection and 22 Ghidra operations shipped on Linux/macOS; Windows analysis blocked |
| [0002: Controlled JavaScript replay authority and sandbox policy](0002-controlled-replay-authority-and-sandbox.md) | Superseded | Historical design; the controlled JavaScript replay tool was removed |
| [0003: Managed-code evidence and provider boundary](0003-managed-code-evidence-and-provider-boundary.md) | Partially superseded | Seven static managed tools remain; runtime planning removed |
| ADR | Status | Implementation |
| ------------------------------------------------------------------------------------------------------------------ | -------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| [0001: Provider selection and analysis profiles](0001-provider-selection-and-analysis-profiles.md) | Accepted | Provider selection and 22 Ghidra operations shipped on Linux/macOS; experimental Windows x64 P0 with bundled native controls |
| [0002: Controlled JavaScript replay authority and sandbox policy](0002-controlled-replay-authority-and-sandbox.md) | Superseded | Historical design; the controlled JavaScript replay tool was removed |
| [0003: Managed-code evidence and provider boundary](0003-managed-code-evidence-and-provider-boundary.md) | Partially superseded | Seven static managed tools remain; runtime planning removed |
+19 -3
View File
@@ -24,14 +24,19 @@ graph TD
GHIDRA["src/ghidra/<br/>Ghidra discovery, profile & function analysis<br/>snapshot, Unix/Windows transport, bounded lifecycle"]
AUX["src/artifacts/ + src/native/<br/>disjoint artifact and native capabilities"]
BROWSER["src/browser/<br/>Loopback CDP transport<br/>exact-origin passive observation"]
DOTNET["src/dotnet/<br/>Managed static metadata provider<br/>PE/CLI metadata inventory, members, IL"]
REFERENCE["src/reference/<br/>Filesystem reference-source reader<br/>bounded traversal, validation, errors"]
end
subgraph "Provider Process Foundation"
PROCESS["src/process/<br/>owned process groups, private roots<br/>deadlines, bounded file reads and diagnostics, cleanup"]
WINDOWS["src/windows/<br/>Windows host boundary adapters<br/>package loader, opaque handles, owned jobs and private runtimes"]
WINDOWS_NATIVE["native/windows/src/<br/>Node-API implementation<br/>NTFS admission, protected DACLs and atomic Job Object assignment"]
end
subgraph "Contracts Layer"
CONTRACTS["src/contracts/<br/>Caller-visible schemas for analysis, managed, browser, Electron, application, and session tools"]
ERRORS["src/contracts/errorSchemas.ts<br/>Shared analysis error schemas<br/>CLI diagnostics, generated error catalog"]
end
subgraph "Domain Layer"
@@ -46,12 +51,17 @@ graph TD
TESTS["tests/<br/>Vitest suite<br/>fixtures/ holds fake launcher, bridge, and CDP seams"]
end
subgraph "Evaluation"
EVALUATION["src/evaluation/<br/>Agent release evaluation<br/>session transcript scoring"]
end
DISPATCH --> CLI
DISPATCH --> MAIN
MAIN --> CONFIG
MAIN --> SERVER
MAIN --> APP
CLI --> APP
CLI --> ERRORS
APP --> SESSION
SESSION --> REGISTRY
REGISTRY --> HOPPER
@@ -62,25 +72,31 @@ graph TD
SERVER --> CONTRACTS
SERVER --> APP
APP --> BROWSER
APP --> REPLAY
APP --> DOTNET
DOTNET --> DOMAIN
HOPPER --> HOPPER_BRIDGE
GHIDRA --> GHIDRA_BRIDGE
HOPPER --> PROCESS
GHIDRA --> PROCESS
GHIDRA --> WINDOWS
PROCESS --> WINDOWS
WINDOWS --> WINDOWS_NATIVE
APP --> PROCESS
APP --> DOMAIN
JS_RECON --> AUX
JS_RECON --> DOMAIN
APP --> REFERENCE
REFERENCE --> DOMAIN
CONTRACTS --> DOMAIN
HOPPER --> DOMAIN
GHIDRA --> DOMAIN
AUX --> DOMAIN
BROWSER --> DOMAIN
REPLAY --> DOMAIN
PROCESS --> DOMAIN
TESTS -.-> MAIN
TESTS -.-> HOPPER
TESTS -.-> GHIDRA
TESTS -.-> PROCESS
TESTS -.-> BROWSER
TESTS -.-> REPLAY
TESTS -.-> EVALUATION
TESTS -.-> ERRORS
+85 -2
View File
@@ -1,6 +1,6 @@
# DOS MZ analysis with Ghidra
# DOS MZ and COM analysis with Ghidra
REA can analyze DOS MZ executables through the bring-your-own Ghidra adapter.
REA can analyze DOS MZ executables and explicitly selected COM images through the bring-your-own Ghidra adapter.
The Linux x64 verification lane exercises actual 16-bit disassembly and
decompilation through the CLI and stdio MCP. It requires the same Ghidra
12.1.4 and 64-bit JDK 21 installation as other Ghidra sessions; no DOS emulator
@@ -13,6 +13,9 @@ rea inspect /absolute/path/to/legacy.exe --provider ghidra --json
rea search /absolute/path/to/legacy.exe entry --kind procedures --provider ghidra --json
rea instructions /absolute/path/to/legacy.exe entry --provider ghidra --json
rea function /absolute/path/to/legacy.exe entry --provider ghidra --json
rea inspect-native-load-image /absolute/path/to/legacy.exe --provider ghidra --json
rea read-bytes /absolute/path/to/legacy.exe 0x10000 --length 16 --provider ghidra --json
rea address-to-file-offset /absolute/path/to/legacy.exe 0x10000 --provider ghidra --json
```
Use an observed procedure name or address from discovery when the target does
@@ -38,6 +41,43 @@ The profile also commits `function_body_evidence: complete-inclusive-ranges-v1`,
so snapshots from older length-only Ghidra results do not satisfy the current
profile.
## Headerless COM images
COM has no identifying header. Select its interpretation explicitly; neither the
`.com` suffix nor arbitrary unrecognized bytes are enough to admit it.
```bash
rea inspect /absolute/path/to/legacy.com --target-format dos-com --provider ghidra --json
rea function /absolute/path/to/legacy.com 0x10100 --target-format dos-com --provider ghidra --json
rea inspect-native-load-image /absolute/path/to/legacy.com --target-format dos-com --provider ghidra --json
```
```json
{
"name": "open_binary",
"arguments": {
"path": "/absolute/path/to/legacy.com",
"format": "dos-com",
"provider_id": "ghidra"
}
}
```
The caller's interpretation applies to the complete file, even if its filename
suggests another format. Files must contain 1..65280 bytes: the 64 KiB COM segment
minus the 256-byte PSP prefix. Ghidra uses `BinaryLoader` with real-mode language
and maps file offset zero at `1000:0100` (linear `0x10100`). A packaged pre-analysis
script seeds the entry function and CS/DS/ES/SS context `0x1000`. These settings
and the preparation policy are committed in the analysis profile; a failed
preparation prevents the resident bridge from serving results.
Load-image verification checks all original and modified file bytes, complete
source mapping/memory digests, absence of relocations, entry and measured register
context. The context is imposed for analysis, not observed from execution. PSP
memory, initial stack contents/SP, DOS interrupts and PC-98 devices are not
modeled. COM has no MZ header, relocation table or appended-overlay model; all
selected bytes belong to its analysis module. The original file stays unchanged.
## Addresses and function extent
Returned default-space addresses are linear byte coordinates. A Ghidra
@@ -71,6 +111,30 @@ Ghidra's database observation, not a proof of original source ownership or
exhaustive code discovery. Providers that do not report complete ranges return
`available: false` and an explicit reason.
## Loaded-image evidence
`inspect_native_load_image` independently checks the immutable session snapshot
against the loaded Ghidra Program. It measures complete original and modified
FileBytes digests, every source mapping and its memory digest, relocation records
(including multiplicity), and external entry points. It verifies MZ header and
module partitions, relocation fixups and linear coordinates rather than relying
on the imported executable SHA alone.
The result is `verified`, `mismatch`, or `unsupported`. Every check retains its
expected and observed values. A memory-digest mismatch identifies the source
range's file offset and analysis address; it does not locate the first differing
byte inside that range. Mapping ends are **inclusive**, unlike the exclusive ends
from `list_segments`. Appended overlays remain in source-file identity and are
excluded from initialized module coverage. Uninitialized allocations are reported;
their contents and DOS runtime semantics are not verified. Formats other than MZ and explicit COM return
`unsupported` with measured observations, not a successful MZ verification.
`read_bytes` returns initialized provider memory, including loader fixups; an
unmapped or uninitialized byte ends the read with an explicit returned length and
`complete: false`. `address_to_file_offset` uses the provider's source mapping;
unmapped, uninitialized and ambiguous mappings fail explicitly. A relocated word
can differ from the original file word even when its source offset is known.
## Coverage boundaries
Static decompilation does not execute the target or emulate BIOS, DOS
@@ -103,3 +167,22 @@ executable fixtures, an emulator, or an existing analysis database.
Provider p-code representations can contain process-specific address-space selector
tokens. The lane preserves those reported values and compares stable dossier
observations rather than asserting cross-process identity of raw p-code.
## Function annotations
`annotate_native_function` changes the name and/or comments at one exact local function entry, verifies readback, and returns a refreshed dossier. This is useful when recording recovered DOS function roles; it does not claim original-source names. Name writes preserve the existing namespace; readback returns the fully qualified name used by function inventories. Regular comments map to Ghidra PRE comments and inline comments to EOL comments. Empty text clears a comment; omitted fields preserve it. The whole edit rolls back if a setter, readback or analysis fails.
```json
{
"procedure": "0x10100",
"name": "entry",
"comment": "Recovered startup role",
"inline_comment": "Inspect segment setup"
}
```
```bash
rea annotate-native-function /local/program.com 0x10100 --target-format dos-com --provider ghidra --name entry --comment 'Recovered startup role' --json
```
The CLI returns the updated analysis before closing its isolated session. MCP edits remain visible to later reads until `close_binary`. Original bytes remain unchanged, database edits are discarded on close, and immutable analysis snapshots are invalidated after edits. This operation does not save a Ghidra project, change ABI/types/body ranges, patch instructions, or emulate a DOS runtime. Windows P0 does not admit it.
+39 -19
View File
@@ -36,7 +36,7 @@ Setup continues to pin persistent MCP registrations to the exact version that
performed setup. Running current setup later migrates unversioned or older
managed registrations through the normal reviewed setup transaction.
REA supports Node.js 22.19+ and 24.11+ (including newer releases). It uses the npm already paired with that runtime and never upgrades Node.js, npm, or Homebrew.
REA supports Node.js 22.x (>=22.19), 24.x (>=24.11), and 26+. Node.js 23, 25, and prereleases are unsupported. It uses the npm already paired with that runtime and never upgrades Node.js, npm, or Homebrew.
Running `npm install rea-agents` without `--global` installs the executable only
in the current project's `node_modules/.bin`; it does not make `rea` available
@@ -77,6 +77,7 @@ Setup can configure these clients for REA's local MCP server:
| OpenCode | `opencode` |
| Antigravity | `antigravity` |
| GitHub Copilot CLI | `copilot_cli` |
| Command Code | `commandcode` |
| VS Code | `vscode` |
## Review setup changes
@@ -212,22 +213,28 @@ copying license secrets into logs, or killing unrelated Hopper processes.
## Ghidra
REA connects to an existing Ghidra installation on Linux x64 or macOS x64/arm64.
REA connects to an existing Ghidra installation on Linux x64, macOS x64/arm64,
or experimental Windows x64 P0.
It requires Ghidra 12.1.4 and a 64-bit full JDK 21. On macOS, the installation
must include the native decompiler for the host architecture; REA does not
build it or change Gatekeeper quarantine settings.
The adapter exposes 22 read-only operations: ten inventory/name/search
The adapter exposes 25 read-only operations: thirteen inventory/name/search
operations and twelve function-analysis operations. These cover metadata,
decompilation, assembly, resolved calls, typed references, xrefs, function
dossiers, instructions, and recovered data types. GUI controls and annotation
changes require Hopper.
dossiers, instructions, recovered data types, measured load mappings, loaded
memory bytes, and observed file offsets. Independent load-image attestation
supports DOS MZ and explicitly selected COM; PE returns its measurements with that limitation.
On Linux and macOS, `annotate_native_function` also edits a function name and/or
entry comments atomically and returns refreshed analysis. These session metadata
edits leave executable bytes unchanged and are discarded on close. GUI controls
require Hopper; Windows P0 remains read-only.
Windows Ghidra operations are currently unavailable. The adapter reports
`unsupported_host` until verified Job Object process ownership, private runtime
DACLs, and reparse-safe path admission are implemented. The
[Windows Ghidra P0 guide](windows-ghidra-p0.md) describes the intended boundary
and remaining controls.
Windows P0 admits native x86-64 PE applications on fixed local NTFS volumes.
The npm package bundles native Job Object ownership, protected private runtime
DACLs, and handle-based path admission; no separate addon installation is needed.
See the [Windows Ghidra P0 guide](windows-ghidra-p0.md) for verified scope and
limitations.
Extract Ghidra and install the JDK outside REA, then export absolute paths:
@@ -238,7 +245,7 @@ rea doctor --json
rea setup
```
For Windows diagnostics, use the same installation paths in PowerShell. These settings do not enable the blocked analysis operations:
On Windows, configure the existing installation in PowerShell:
```powershell
$env:GHIDRA_INSTALL_DIR = "C:\tools\ghidra_12.1.4_PUBLIC"
@@ -251,8 +258,8 @@ rea providers --json
REA skill after approval. Direct registrations use Node to launch REA's entry
script; package-runner registrations use the pinned `npx` command. Hopper
installation remains unavailable on Windows. Setup never installs Ghidra,
Java, or Python, and agent registration does not enable blocked Ghidra
operations. See [Windows Ghidra P0](windows-ghidra-p0.md) for provider diagnostics.
Java, or Python. It preserves valid detected Ghidra/JDK settings in agent
registrations. See [Windows Ghidra P0](windows-ghidra-p0.md) for provider diagnostics.
Doctor validates the platform, architecture, application version,
`support/analyzeHeadless` or `support/analyzeHeadless.bat`, Java
@@ -267,8 +274,8 @@ home/cache/config/temp paths. REA passes `-readOnly`, `-deleteProject`, uses
Ghidra's default analysis and resource settings, and loads its packaged Java
bridge via `-scriptPath`; it never opens an existing user project. Linux and
macOS use a current-user-only local bridge socket and descriptor. The
experimental Windows transport uses authenticated IPv4 loopback, but missing
native ownership and path controls keep Windows operations unavailable.
experimental Windows transport uses authenticated IPv4 loopback with a
private native-owned bearer descriptor and Job Object process ownership.
Operations begin only after default auto-analysis completes. The provider
startup deadline fails the open rather than exposing partial analysis. One
@@ -281,6 +288,14 @@ is no fixed per-operation or response-size ceiling. Unresolved computed calls
remain unknown, reference-kind provenance is preserved, and provider-specific
pseudocode is never treated as original source or Hopper-equivalent text.
Unexpected request failures retain their original internal cause. CLI and MCP
errors expose Error names, messages, and available codes under
`details.diagnostics.failure_cause`; 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
continues. These messages redact known bridge authentication tokens and
preserve local paths and other analysis context.
Run `GHIDRA_INSTALL_DIR=... npm run verify:ghidra` from a source checkout to
compile and analyze debug and stripped host-native fixtures (ELF on Linux x64
or Mach-O on macOS), plus a native DWARF 4 type-layout object. This lane needs a
@@ -315,17 +330,22 @@ server through `npx` with the `mcp` command.
For a client that requires manual configuration, use:
<!-- x-release-please-start-version -->
```json
{
"mcpServers": {
"rea": {
"command": "npx",
"args": ["-y", "rea-agents@latest", "mcp"]
"args": ["-y", "rea-agents@4.0.1", "mcp"]
}
}
}
```
Use an exact `rea-agents@VERSION` in the arguments when a reproducible client
configuration is required. `rea setup` writes the same package-runner shape and
pins it to the exact version that performed setup.
<!-- x-release-please-end -->
Persistent registrations should use one exact package version. `rea setup`
writes the same package-runner shape and pins it to the exact version that
performed setup. Run current setup to refresh an older registration, then
restart the client.
@@ -52,6 +52,23 @@ manifest and graph commitments, JavaScript Application Graph, static
Electron summary, reconstruction statistics, and explicit limitations. It does
not require a live Hopper, Ghidra, browser, or Electron process.
## Large results
Graph and Evidence identifiers hash canonical JSON incrementally, without
assembling a single string for the whole graph. The canonical bytes and existing
identifiers remain unchanged. The opt-in regression check is
`npm run verify:javascript:digests`;
it hashes a value larger than the running Node engine's single-string limit.
Output formatters and MCP transport serialization still assemble whole strings.
For a large CLI result, select the needed fields
before formatting, for example `--format json --filter-output
evidence_id,normalized_result.statistics`. Complete serialization of a result
beyond the engine's string limit is not established by this digest check.
Client framing limits also apply: the pinned Node MCP SDK's stdio transport
defaults to a 10 MiB buffer. Its caller-selected `maxBufferSize` must accommodate
the complete response, including text and structured Evidence projections.
## What is reconstructed
The projector reuses the content-addressed artifact inventory and safe artifact
+8
View File
@@ -437,3 +437,11 @@ The managed-code track advances as reviewable pull requests:
Each implementation PR updates generated product facts only for behavior it
actually ships and states which real-tool checks were performed.
### Method metadata during build comparison
Managed member comparisons report a `metadata` dimension when an observed
MethodDef flags or implementation flags value differs, including accessibility
or synchronization changes. This is separate from the CIL/signature matching
tiers: identical instructions do not establish unchanged method metadata. The
reported difference is static metadata evidence, not proof of runtime behavior.
+11 -7
View File
@@ -8,15 +8,19 @@ registrations, reports their command vectors as aligned, stale, missing, or
invalid, and keeps live-server state `unknown` unless the active connection
supplies identity.
Canonical tool names remain stable, while `tools/list` advertises only the
operations callable for the current target, provider, host, and
negotiated client capabilities. `binary_session.tool_availability` remains the
complete inventory: it explains advertised and hidden operations with stable
availability reasons and remediation. Each entry also reports required and
optional negotiated client features plus the currently missing features.
Opening or closing a target or observing a provider health transition emits
`tools/list` returns the complete canonical tool inventory, including tools that
are currently unavailable. Opening or closing a target or observing a provider
health transition leaves that catalog unchanged and does not emit
`notifications/tools/list_changed`.
Call `binary_session` with `{}` and read `result.tool_availability` to choose a
callable operation for the current target, provider, host, and negotiated client
capabilities. The default result includes the complete inventory with each
tool's availability, reason, and remediation. Each entry also reports required
and optional negotiated client features plus the currently missing features.
The optional inputs `expected_package_version`, `expected_catalog_digest`, and
`expected_server_path` compare the live session with the caller's expectations.
`binary_session.analysis_provider_candidates` is authoritative for deep-engine
discovery. Target-free discovery is sorted by provider ID, reports host
availability and `unknown` target support, and does not create an analysis
+7 -5
View File
@@ -146,12 +146,14 @@ actions may change application data or trigger network activity.
Install Ghidra 12.1.4 and a full 64-bit JDK 21 separately, then configure REA to
use them. Ghidra analysis supports Linux x64 and macOS x64/arm64; macOS requires
the matching native decompiler. Windows Ghidra analysis is unavailable until
Job Object process ownership, private runtime DACLs, and reparse-safe path checks
are implemented and verified. See [Windows Ghidra P0](windows-ghidra-p0.md) and
the matching native decompiler. Experimental Windows x64 P0 admits native
x86-64 PE applications on local NTFS using bundled Job Object ownership,
protected runtime DACLs, and handle-based path admission. See [Windows Ghidra P0](windows-ghidra-p0.md) and
[issue #527](https://github.com/morluto/rea/issues/527).
Ghidra has no GUI or mutation authority, and REA never falls back automatically
to Hopper.
On Linux and macOS, `annotate_native_function` atomically edits a function name
and entry comments in the ephemeral database, returning refreshed analysis
without changing executable bytes. Windows P0 remains read-only. Ghidra has no
GUI authority, and REA never falls back automatically to Hopper.
- `npm run verify:ghidra`: host-native debug/stripped targets, native type layout,
instruction/call facts, value dependencies and process/project cleanup.
+27 -11
View File
@@ -3,22 +3,23 @@
"name": "rea-agents",
"version": "4.0.1",
"sdk": {
"server": "2.0.0",
"client": "2.0.0",
"core": "2.0.0"
"server": "2.3.1",
"client": "2.3.1",
"core": "2.3.1"
},
"skill_version": "24"
},
"tools": {
"total": 116,
"total": 118,
"families": [
{
"id": "direct",
"surface": "official-proxy",
"count": 39,
"count": 41,
"tools": [
"address_name",
"address_to_file_offset",
"annotate_native_function",
"comment",
"current_address",
"current_document",
@@ -27,6 +28,7 @@
"inline_comment",
"inspect_native_data_type",
"inspect_native_instruction",
"inspect_native_load_image",
"list_bookmarks",
"list_documents",
"list_names",
@@ -207,9 +209,12 @@
"version": null,
"capabilities": [
"address_name",
"address_to_file_offset",
"analyze_function",
"annotate_native_function",
"inspect_native_data_type",
"inspect_native_instruction",
"inspect_native_load_image",
"list_documents",
"list_names",
"list_procedures",
@@ -222,6 +227,7 @@
"procedure_info",
"procedure_pseudo_code",
"procedure_references",
"read_bytes",
"read_function_instructions",
"resolve_containing_procedure",
"resolve_native_call_targets",
@@ -451,6 +457,12 @@
"format": "copilot_cli",
"configuration": "managed"
},
{
"id": "commandcode",
"display_name": "Command Code",
"format": "commandcode",
"configuration": "managed"
},
{
"id": "vscode",
"display_name": "VS Code",
@@ -459,11 +471,13 @@
}
],
"cli": {
"primary_count": 69,
"primary_count": 73,
"commands": [
"address-to-file-offset",
"analyze",
"analyze-javascript-application",
"analyze-web-bundle",
"annotate-native-function",
"build-reconstruction-obligation-ledger",
"capabilities",
"capture-browser-scenario",
@@ -504,6 +518,7 @@
"inspect-native-data-type",
"inspect-native-dispatch-metadata",
"inspect-native-instruction",
"inspect-native-load-image",
"inspect-plist",
"inspect-signature",
"inspect-web-page",
@@ -517,6 +532,7 @@
"observe-web-session",
"project-managed-application-graph",
"providers",
"read-bytes",
"reconcile-javascript-runtime",
"resolve-native-call-targets",
"search",
@@ -540,15 +556,15 @@
},
"runtime_catalog": {
"counts": {
"cli_commands": 69,
"mcp_tools": 116,
"cli_commands": 73,
"mcp_tools": 118,
"mcp_prompts": 6
},
"digests": {
"tools_sha256": "7849b6f39bed200cfbf5f4d09ba3f9e0661824efb5753ae2edde8ef2fb66535e",
"tools_sha256": "bbd9aacf7bb0bc54a8f8743491583482e1176252513d99780a309d0fddeb3df0",
"prompts_sha256": "4762db348821fec787a5b8c6423f2c48a71f6f0ec2afee97b16ad69030ec504b",
"combined_sha256": "5bb3f994a3c4d0c87a34ff5aab4e28141b5fa6f3a98b5ae7e95686d85d9d983e",
"providers_sha256": "2ae8b85b20be338739e500549d275e78e875aaa10235d2ca283f0ade7787da90"
"combined_sha256": "b4f7e5860d90b029876b58fe7cd4a8041fef1f2add23440e37e90827d808e503",
"providers_sha256": "e094c361b60ec930a6062a1a90ee05536ce411541dba5b51ace7e2da2ba25af0"
}
}
}
+26 -20
View File
@@ -4,18 +4,22 @@ Ghidra read-only analysis is available on Linux x64 and macOS x64/arm64.
Install Ghidra 12.1.4 and a full 64-bit JDK 21 separately, then configure REA to
use them. macOS installations need the matching native decompiler.
REA imports one target into a temporary project and exposes 22 read-only
REA imports one target into a temporary project and exposes 25 read-only
operations after analysis completes. They cover inventories, search,
decompilation, assembly, function metadata, resolved calls, references, control
flow, instructions, and recovered types. Results identify the provider version,
analysis settings, target digest, and any unavailable or incomplete facts.
Ghidra does not expose Hopper's GUI or annotation operations.
On Linux and macOS, `annotate_native_function` additionally edits names and entry
comments atomically, verifies readback, and returns refreshed function analysis.
Changes live only in the session database and leave executable bytes unchanged.
Ghidra does not expose GUI controls; Windows P0 remains read-only.
Windows Ghidra analysis is unavailable, including on a correctly configured
Ghidra/JDK host. Job Object process ownership, private runtime DACLs, and
reparse-safe path checks are not implemented. Package and adapter tests do not
establish real Windows analysis support. See [Windows Ghidra P0](windows-ghidra-p0.md)
and [issue #527](https://github.com/morluto/rea/issues/527).
Windows x64 P0 supports native x86-64 PE applications on local NTFS with
bundled Job Object ownership, protected runtime DACLs, and handle-based path
admission. Real ordinary-user verification covers all 25 read-only operations
through the packaged CLI and MCP, target integrity, and cleanup. This remains
an experimental boundary; see [Windows Ghidra P0](windows-ghidra-p0.md) and
[issue #527](https://github.com/morluto/rea/issues/527).
[ADR-0001](adr/0001-provider-selection-and-analysis-profiles.md) fixes the
provider registry, deterministic selection, target binding, analysis profile,
@@ -73,7 +77,7 @@ token-free endpoint record, but cannot start while the native authority is
unavailable. Its `taskkill` cleanup code does not establish Job Object ownership,
private DACLs, or reparse-safe paths.
The provider catalog lists the 22 Ghidra operations. GUI cursor,
The provider catalog lists the 25 Ghidra operations. GUI cursor,
navigation, and mutation operations remain absent; the router therefore
reports them unavailable instead of borrowing Hopper semantics or inferring
capability from a successful import.
@@ -122,12 +126,14 @@ Mach-O target coverage. It requires `clang`, LLD, and `lld-link`; set
these tools before compilation. Keeping this matrix separate lets Linux
host/provider acceptance run with only the host compiler.
`npm run verify:ghidra:windows` remains blocked by the missing Windows native
authority. After those controls are implemented, the lane must check the
source-owned native x86-64 PE fixture, all read-only operations,
target/snapshot/import SHA-256 linkage, and project, endpoint, process, and
runtime cleanup. The existence of this verifier is not evidence that Windows
Ghidra analysis works.
`npm run verify:ghidra:windows` checks the source-owned native x86-64 PE
fixture, all 25 read-only operations, target/snapshot/import SHA-256 linkage,
and project, endpoint, process, and runtime cleanup. The independent native
lane checks DACLs, handle admission, cancellation, and Job Object lifecycle.
`npm run verify:ghidra:windows:package` packs and installs REA into an isolated
prefix, then checks ordinary-user CLI/MCP operations against canonical contracts.
All lanes require matching native controls; package startup alone establishes
only package compatibility.
## Shared provider-process foundation
@@ -149,12 +155,12 @@ only the generic process mechanisms.
## Shortlist
| Provider | License / automation surface | What it brings | REA fit and blockers |
| ------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Ghidra](https://github.com/NationalSecurityAgency/ghidra) | Apache-2.0 source license; `analyzeHeadless`, Java APIs, and PyGhidra | Static analysis, multiple processors and formats, scripting, and project/database workflows | 22 read-only operations shipped on Linux/macOS with installation checks, temporary projects, a serial API queue, and real ELF/PE/Mach-O conformance. Windows analysis is blocked; GUI and mutation operations are unavailable. |
| [Rizin](https://github.com/rizinorg/rizin) / [rz-pipe](https://github.com/rizinorg/rz-pipe) | Rizin repository contains LGPL-3.0 and GPL-3.0 components; `rizin`, `rz-bin`, and language bridges through `rzpipe` | Portable CLI analysis, disassembly/debugging, many architectures and file formats, JSON command output | Good candidate for a process-backed Linux provider and fast metadata fallback. License/component inventory must be preserved; command output needs version-pinned parsers and semantic conformance before evidence is trusted. |
| [LIEF](https://github.com/lief-project/LIEF) | Apache-2.0; C++, Python, and other bindings | Deterministic parsing and modification of ELF, PE, Mach-O, COFF, and related executable formats; headers, sections, symbols, relocations, and functions | Best near-term complement, not a decompiler replacement. It can cover format metadata and artifact evidence without a long-lived analysis process; function semantics, pseudocode, CFG, and cross-reference parity remain out of scope unless separately demonstrated. |
| [Binary Ninja](https://docs.binary.ninja/dev/index.html) | API/documentation components are MIT, while the analysis product is licensed by edition; commercial, Ultimate, or Headless license is required for headless automation | Python/Core/C++/Rust APIs, headless loading, IL layers, function analysis, plugins, and configurable analysis | Strong technical fit for a native provider, especially function dossiers. Commercial licensing, license-secret handling, native runtime packaging, and multithreaded lifecycle rules are material deployment blockers. |
| Provider | License / automation surface | What it brings | REA fit and blockers |
| ------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Ghidra](https://github.com/NationalSecurityAgency/ghidra) | Apache-2.0 source license; `analyzeHeadless`, Java APIs, and PyGhidra | Static analysis, multiple processors and formats, scripting, and project/database workflows | 25 read-only operations shipped on Linux/macOS with installation checks, temporary projects, a serial API queue, and real ELF/PE/Mach-O conformance. Experimental Windows x64 P0 supports native x86-64 PE on local NTFS with bundled native controls and ordinary-user CLI/MCP verification; Linux/macOS additionally support atomic session function annotations; Windows mutation and all Ghidra GUI operations are unavailable. |
| [Rizin](https://github.com/rizinorg/rizin) / [rz-pipe](https://github.com/rizinorg/rz-pipe) | Rizin repository contains LGPL-3.0 and GPL-3.0 components; `rizin`, `rz-bin`, and language bridges through `rzpipe` | Portable CLI analysis, disassembly/debugging, many architectures and file formats, JSON command output | Good candidate for a process-backed Linux provider and fast metadata fallback. License/component inventory must be preserved; command output needs version-pinned parsers and semantic conformance before evidence is trusted. |
| [LIEF](https://github.com/lief-project/LIEF) | Apache-2.0; C++, Python, and other bindings | Deterministic parsing and modification of ELF, PE, Mach-O, COFF, and related executable formats; headers, sections, symbols, relocations, and functions | Best near-term complement, not a decompiler replacement. It can cover format metadata and artifact evidence without a long-lived analysis process; function semantics, pseudocode, CFG, and cross-reference parity remain out of scope unless separately demonstrated. |
| [Binary Ninja](https://docs.binary.ninja/dev/index.html) | API/documentation components are MIT, while the analysis product is licensed by edition; commercial, Ultimate, or Headless license is required for headless automation | Python/Core/C++/Rust APIs, headless loading, IL layers, function analysis, plugins, and configurable analysis | Strong technical fit for a native provider, especially function dossiers. Commercial licensing, license-secret handling, native runtime packaging, and multithreaded lifecycle rules are material deployment blockers. |
## Recommended order
+14 -13
View File
@@ -43,12 +43,14 @@ REA setup lets you select agent integration and optional Hopper installation.
It installs the bundled workflow, configures detected agents, and can save
verified paths for an existing Ghidra installation. It configures Claude Code,
Claude Desktop, Codex, Cursor, Gemini CLI, Windsurf, Devin, OpenCode, Antigravity,
GitHub Copilot CLI, and VS Code using each client's configuration format.
GitHub Copilot CLI, Command Code, and VS Code using each client's configuration format.
Ghidra analysis supports Linux x64 and macOS x64/arm64 with Ghidra 12.1.4 and a
64-bit full JDK 21. macOS also requires the matching native decompiler. The
adapter exposes ten inventory operations and twelve function-analysis
operations, for 22 read-only operations total. Approved setup saves verified
adapter exposes thirteen inventory operations and twelve function-analysis
operations, for 25 read-only operations total. Linux and macOS additionally support
atomic function-name and entry-comment edits with refreshed analysis; metadata
is discarded on close and executable bytes stay unchanged. Approved setup saves verified
installation paths in agent configurations without installing or changing
Ghidra or Java.
@@ -57,11 +59,11 @@ a native type-layout object. A separate lane covers AArch64 ELF, PE, and
Mach-O cross-target fixtures. See [testing](testing.md) for the prerequisites
and exact commands.
Windows Ghidra operations remain unavailable until REA implements verified
Job Object process ownership, private runtime DACLs, and reparse-safe path
admission. Windows package and adapter tests do not establish a usable real
Ghidra session. The [Windows P0 guide](windows-ghidra-p0.md) describes the
intended boundary and remaining requirements.
Experimental Windows x64 P0 now supplies bundled Job Object ownership,
protected runtime DACLs, and handle-based admission for native x86-64 PE
applications on local NTFS. Real ordinary-user CLI/MCP verification covers
all 25 read-only operations and cleanup. The [Windows P0 guide](windows-ghidra-p0.md)
describes this boundary and unverified broader coverage.
## Ghidra maintenance boundary
@@ -71,11 +73,10 @@ not expected to match; unresolved targetless flow remains unknown. Automatic
Ghidra acquisition, if ever added, remains a separately planned and approved
related-tool change; setup must never install Java.
Before enabling Windows Ghidra operations, add current-user-only DACL creation and
readback, handle-based reparse-point-safe path authority, a DACL-protected IPC
backend, and Job Object assignment before provider execution. Process capture,
Hopper, and broad filesystem-sensitive workflows remain separate Windows
projects rather than implied parity.
Maintain Windows P0 with independent DACL readback, handle-based admission,
private authenticated IPC, and Job Object assignment before provider execution.
Process capture, Hopper, and broad filesystem-sensitive workflows remain
separate Windows projects; P0 does not imply their parity.
## Capability-selective setup
+17 -5
View File
@@ -103,8 +103,15 @@ that a host or target is covered when it was skipped.
| `npm run verify:ghidra:switch` | Linux x64 ELF; GCC/Clang optimized and stripped switch fixtures | GCC, Clang, GNU nm/objdump/strip, Ghidra 12.1.4, and full JDK 21 |
| `npm run verify:ghidra:aarch64-jump-table` | Any supported Ghidra host; AArch64 ELF; byte/halfword tables; host ARM64 Mach-O | Clang with AArch64 target support, Ghidra 12.1.4, and full JDK 21 |
| `npm run verify:ghidra:cross-format` | Any supported Ghidra host; also analyzes AArch64 ELF, x86-64 PE, and x86-64 Mach-O | `clang`, LLD, and `lld-link` in addition to host-lane prerequisites |
| `npm run verify:ghidra:windows` | Controlled Windows x64 with native x86-64 PE | Ghidra 12.1.4, full JDK 21, and the Windows P0 fixture toolchain |
| `npm run verify:ghidra:windows` | Controlled Windows x64 with native x86-64 PE | Ghidra 12.1.4, full JDK 21, and the matching native artifact |
Windows native conformance runs with `npm run verify:windows-native` and does
not require Ghidra or Java. An optional independently compiled Windows fixture
adds in-place reparse, breakaway, environment, and token observations.
`npm run verify:ghidra:windows:package` additionally packs and installs REA into
an isolated prefix and runs ordinary-user CLI/MCP operations against their
canonical schemas. Run the controlled fixture generator before that lane, or
supply an installed package root and an explicit fixture as arguments.
The host-native Ghidra lane also verifies native value tracing through the
production CLI and a separate stdio MCP process. It compares complete dependency
graphs, validates Evidence and upstream/workflow profiles, checks capability
@@ -153,6 +160,13 @@ the stable observation comparison. Linux x64 is verified; macOS DOS remains
unverified. This lane is separate from host-native and optional cross-format
verification. See [DOS analysis](ghidra-dos.md).
`npm run verify:ghidra:com` uses a generated headerless fixture with no compiler,
DOS emulator or game data. It exercises explicit admission, BinaryLoader entry
preparation, measured register context, whole-file byte readback, source offsets,
unmapped PSP/partial reads, actual decompilation, CLI/MCP parity and owned cleanup.
It has the same Ghidra/JDK prerequisites as the MZ lane. Neither lane claims DOS
runtime or PC-98 device execution.
## Apple Interface Builder archives
`npm run verify:interface-builder` compiles the source-owned AppKit XIB into a
@@ -182,8 +196,7 @@ behavior, and complete CI evidence before merging.
| `npm run test:watch:all` | Changed tests from every project; builds at startup, so rebuild after production edits before relying on compiled tests |
| `npm run check:changed` | Cached typecheck/lint and branch-related source feedback |
| `npm run check:pr` | Opt-in complete local deterministic gate and generated-file checks |
| `npm run docs:check` | Committed generated-document freshness, without API HTML rendering |
| `npm run docs:api:cached` | Explicit cached API HTML rendering |
| `npm run docs:check` | Committed generated-document freshness |
For example:
@@ -230,8 +243,7 @@ process-global, and other boundary projects retain per-file isolation.
`npm test`, `npm run docs:check`, and `npm run docs:generate` share
repository-local locks and fail fast when the same class of command is already
running. The `npm test` build is inside that lock. `check:pr` runs its test task
before starting generated-document validation. TypeDoc rendering is a separate
command and CI step.
before starting generated-document validation.
Vitest and Node persistent compile caches are deliberately not enabled by
default. To evaluate repeated local runs, opt in for both cold and warm
+5 -5
View File
@@ -55,7 +55,7 @@ harm_rank,location,trigger,current_copy,user_risk,proposed_replacement,implement
45.5,src/application/Uninstall.ts:removeClient restore,Configuration update fails and restoring the original also fails,"Configuration could not be updated or restored. Restore its `.rea.backup` manually, then rerun uninstall.","High risk; persistent configuration may be damaged, but retained backup is authoritative",Keep new recovery copy,implemented,verified by injected restoration failure test
46,src/application/Uninstall.ts:removeManagedPath symlink,Managed cache/state/skill path is a symbolic link,Refused to follow symlink {path}.,Exposes local path and does not explain manual safety check,"REA did not remove this item because its managed path is a symbolic link. Verify the link target before removing it manually.",implemented,focused assertion passed
47,src/application/Uninstall.ts:removeManagedPath failure,Managed item removal fails,{path} could not be removed.,Exposes local path and gives no recovery,"This item could not be removed. Check file permissions, then rerun uninstall.",implemented,verified by injected managed-path removal failure test
48,src/application/Doctor.ts:node,Runtime version is outside supported ranges,Install Node.js 22.19+ or 24.11+.,Low risk; exact dependency recovery,Keep current copy,unchanged,verified by doctor unit test
48,src/application/DoctorDiagnostics.ts:node,Runtime version is outside supported ranges,"Install Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+.",Low risk; exact dependency recovery,Keep current copy,unchanged,verified by doctor unit test
49,src/application/Doctor.ts:host,Host OS/distribution is unsupported,"REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, and 64-bit Arch Linux.",Low risk; clearly states supported choices,Keep current copy,unchanged,verified by doctor unit tests
50,src/application/Doctor.ts:analysis engine,Optional deep-analysis executable cannot be found,"Run rea setup to install Hopper, or set HOPPER_LAUNCHER_PATH.",Low risk in setup-specific diagnostic; exact recovery paths,Keep current copy,unchanged,verified by doctor unit tests
51,src/application/Doctor.ts:target,Optional target path fails shared validation,Supply a readable local app or program path.,Low risk; tells caller valid target class,Keep current copy,unchanged,verified by doctor unit test
@@ -65,7 +65,7 @@ harm_rank,location,trigger,current_copy,user_risk,proposed_replacement,implement
55,src/application/Setup.ts:optional engine,Setup completes without optional deep-analysis engine,Hopper is optional for non-Hopper providers. Rerun with --yes --install-hopper for deep native analysis.,Exposes provider terminology but this is an explanatory setup status rather than an error; recovery command is exact,Keep current copy,unchanged,verified by setup unit test
56,src/application/Setup.ts:doctor fallback,Post-setup diagnostics remain unhealthy,Run rea doctor and apply each reported remediation.,Low risk; delegates to structured per-check recovery,Keep current copy,unchanged,verified by exact setup unit test
57,src/application/Setup.ts:unsupported platform,Platform is neither macOS nor Linux,REA supports Hopper on macOS and selected 64-bit Linux distributions.,Low risk; states support boundary,Keep current copy,unchanged,verified by setup unit test
58,src/application/Setup.ts:unsupported Node,Runtime version cannot run setup,Install Node.js 22.19+ or 24.11+ and rerun setup.,Low risk; exact dependency and retry,Keep current copy,unchanged,verified by setup host tests
58,src/application/SetupHost.ts:unsupported Node,Runtime version cannot run setup,"Install Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+ and rerun setup.",Low risk; exact dependency and retry,Keep current copy,unchanged,verified by setup host tests
59,src/application/Setup.ts:unsupported macOS,macOS version is missing or older than 12,Upgrade to macOS 12 or newer.,Low risk; exact support floor,Keep current copy,unchanged,verified by setup host tests
60,src/application/Setup.ts:unsupported Linux,Linux distribution is outside supported set,"REA supports Hopper on Ubuntu 24.04+, Fedora 41+, and 64-bit Arch Linux.",Low risk; exact supported alternatives,Keep current copy,unchanged,verified by setup unit test
61,src/application/ProcessCli.ts:readJson read,Process scenario or evidence file cannot be read,Raw filesystem exception through CLI framework,Can expose local paths/codes and no recovery,"Process input file could not be read. Check that the path exists and is readable.",implemented,verified by focused CLI test
@@ -83,11 +83,11 @@ harm_rank,location,trigger,current_copy,user_risk,proposed_replacement,implement
74,install.sh:unknown option,Installer receives an unsupported flag,unknown option with caller-provided flag,Low risk; identifies offending input,Keep current copy,unchanged,verified by shell branch inspection
75,install.sh:platform,Installer runs outside macOS or supported Linux,REA supports macOS and selected 64-bit Linux distributions.,Low risk; states support boundary,Keep current copy,unchanged,verified by shell branch inspection
76,install.sh:curl missing,curl is absent,curl is required.,No recovery instruction,"curl is required. Install curl, then rerun this installer.",implemented,verified by exact missing-curl installer test
77,install.sh:node missing,node is absent,Node.js 22.19+ or 24.11+ is required; install it from nodejs.org and retry.,Low risk; exact versions and recovery,Keep current copy,unchanged,verified by shell branch inspection
77,install.sh:node missing,node is absent,"Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+ is required; install it from nodejs.org and retry.",Low risk; exact versions and recovery,Keep current copy,unchanged,verified by shell branch inspection
78,install.sh:npm missing,npm is absent,npm is required; install it with Node.js and retry.,Low risk; exact recovery,Keep current copy,unchanged,verified by shell branch inspection
79,install.sh:node unreadable,node exists but does not report a parseable version,could not determine the active Node.js version.,No cause-local recovery,"The active Node.js version could not be read. Check that node works and is on PATH, then retry.",implemented,verified by exact unreadable-Node-version installer test
80,install.sh:Node 22 floor,Node 22 minor version is below 19,Node.js VERSION is unsupported; use Node.js 22.19+ or 24.11+.,Low risk; exact detected version and supported alternatives,Keep current copy,unchanged,verified by exact installer test using Node 20 and branch inspection
81,install.sh:Node 24 floor,Node 24 minor version is below 11,Node.js VERSION is unsupported; use Node.js 24.11 or newer.,Low risk; exact detected version and floor,Keep current copy,unchanged,verified by shell branch inspection
80,install.sh:Node 22 floor,Node 22 minor version is below 19,"Node.js VERSION is unsupported; use Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+.",Low risk; exact detected version and supported alternatives,Keep current copy,unchanged,verified by exact installer test using Node 20 and branch inspection
81,install.sh:Node 24 floor,Node 24 minor version is below 11,"Node.js VERSION is unsupported; use Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+.",Low risk; exact detected version and floor,Keep current copy,unchanged,verified by shell branch inspection
82,install.sh:version syntax,Explicit version is not exact semantic version,version must be an exact semantic version.,Low risk; exact correction,Keep current copy,unchanged,verified by shell branch inspection
83,install.sh:release lookup,Latest GitHub release request fails,could not resolve the latest GitHub release.,No fallback despite supporting pinned versions,"The latest REA release could not be resolved. Check network access or pass --version VERSION, then retry.",implemented,verified by exact release-lookup installer test
84,install.sh:release response,Latest release response is not valid expected JSON,Node JSON parser stack followed by the safe release-response message,Leaks a parser stack and buries recovery guidance,The release response was invalid. Retry later or pass --version VERSION.,implemented,verified by exact malformed-release test with parser stderr suppressed
1 harm_rank location trigger current_copy user_risk proposed_replacement implementation_status verification_result
55 45.5 src/application/Uninstall.ts:removeClient restore Configuration update fails and restoring the original also fails Configuration could not be updated or restored. Restore its `.rea.backup` manually, then rerun uninstall. High risk; persistent configuration may be damaged, but retained backup is authoritative Keep new recovery copy implemented verified by injected restoration failure test
56 46 src/application/Uninstall.ts:removeManagedPath symlink Managed cache/state/skill path is a symbolic link Refused to follow symlink {path}. Exposes local path and does not explain manual safety check REA did not remove this item because its managed path is a symbolic link. Verify the link target before removing it manually. implemented focused assertion passed
57 47 src/application/Uninstall.ts:removeManagedPath failure Managed item removal fails {path} could not be removed. Exposes local path and gives no recovery This item could not be removed. Check file permissions, then rerun uninstall. implemented verified by injected managed-path removal failure test
58 48 src/application/Doctor.ts:node src/application/DoctorDiagnostics.ts:node Runtime version is outside supported ranges Install Node.js 22.19+ or 24.11+. Install Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+. Low risk; exact dependency recovery Keep current copy unchanged verified by doctor unit test
59 49 src/application/Doctor.ts:host Host OS/distribution is unsupported REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, and 64-bit Arch Linux. Low risk; clearly states supported choices Keep current copy unchanged verified by doctor unit tests
60 50 src/application/Doctor.ts:analysis engine Optional deep-analysis executable cannot be found Run rea setup to install Hopper, or set HOPPER_LAUNCHER_PATH. Low risk in setup-specific diagnostic; exact recovery paths Keep current copy unchanged verified by doctor unit tests
61 51 src/application/Doctor.ts:target Optional target path fails shared validation Supply a readable local app or program path. Low risk; tells caller valid target class Keep current copy unchanged verified by doctor unit test
65 55 src/application/Setup.ts:optional engine Setup completes without optional deep-analysis engine Hopper is optional for non-Hopper providers. Rerun with --yes --install-hopper for deep native analysis. Exposes provider terminology but this is an explanatory setup status rather than an error; recovery command is exact Keep current copy unchanged verified by setup unit test
66 56 src/application/Setup.ts:doctor fallback Post-setup diagnostics remain unhealthy Run rea doctor and apply each reported remediation. Low risk; delegates to structured per-check recovery Keep current copy unchanged verified by exact setup unit test
67 57 src/application/Setup.ts:unsupported platform Platform is neither macOS nor Linux REA supports Hopper on macOS and selected 64-bit Linux distributions. Low risk; states support boundary Keep current copy unchanged verified by setup unit test
68 58 src/application/Setup.ts:unsupported Node src/application/SetupHost.ts:unsupported Node Runtime version cannot run setup Install Node.js 22.19+ or 24.11+ and rerun setup. Install Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+ and rerun setup. Low risk; exact dependency and retry Keep current copy unchanged verified by setup host tests
69 59 src/application/Setup.ts:unsupported macOS macOS version is missing or older than 12 Upgrade to macOS 12 or newer. Low risk; exact support floor Keep current copy unchanged verified by setup host tests
70 60 src/application/Setup.ts:unsupported Linux Linux distribution is outside supported set REA supports Hopper on Ubuntu 24.04+, Fedora 41+, and 64-bit Arch Linux. Low risk; exact supported alternatives Keep current copy unchanged verified by setup unit test
71 61 src/application/ProcessCli.ts:readJson read Process scenario or evidence file cannot be read Raw filesystem exception through CLI framework Can expose local paths/codes and no recovery Process input file could not be read. Check that the path exists and is readable. implemented verified by focused CLI test
83 74 install.sh:unknown option Installer receives an unsupported flag unknown option with caller-provided flag Low risk; identifies offending input Keep current copy unchanged verified by shell branch inspection
84 75 install.sh:platform Installer runs outside macOS or supported Linux REA supports macOS and selected 64-bit Linux distributions. Low risk; states support boundary Keep current copy unchanged verified by shell branch inspection
85 76 install.sh:curl missing curl is absent curl is required. No recovery instruction curl is required. Install curl, then rerun this installer. implemented verified by exact missing-curl installer test
86 77 install.sh:node missing node is absent Node.js 22.19+ or 24.11+ is required; install it from nodejs.org and retry. Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+ is required; install it from nodejs.org and retry. Low risk; exact versions and recovery Keep current copy unchanged verified by shell branch inspection
87 78 install.sh:npm missing npm is absent npm is required; install it with Node.js and retry. Low risk; exact recovery Keep current copy unchanged verified by shell branch inspection
88 79 install.sh:node unreadable node exists but does not report a parseable version could not determine the active Node.js version. No cause-local recovery The active Node.js version could not be read. Check that node works and is on PATH, then retry. implemented verified by exact unreadable-Node-version installer test
89 80 install.sh:Node 22 floor Node 22 minor version is below 19 Node.js VERSION is unsupported; use Node.js 22.19+ or 24.11+. Node.js VERSION is unsupported; use Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+. Low risk; exact detected version and supported alternatives Keep current copy unchanged verified by exact installer test using Node 20 and branch inspection
90 81 install.sh:Node 24 floor Node 24 minor version is below 11 Node.js VERSION is unsupported; use Node.js 24.11 or newer. Node.js VERSION is unsupported; use Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+. Low risk; exact detected version and floor Keep current copy unchanged verified by shell branch inspection
91 82 install.sh:version syntax Explicit version is not exact semantic version version must be an exact semantic version. Low risk; exact correction Keep current copy unchanged verified by shell branch inspection
92 83 install.sh:release lookup Latest GitHub release request fails could not resolve the latest GitHub release. No fallback despite supporting pinned versions The latest REA release could not be resolved. Check network access or pass --version VERSION, then retry. implemented verified by exact release-lookup installer test
93 84 install.sh:release response Latest release response is not valid expected JSON Node JSON parser stack followed by the safe release-response message Leaks a parser stack and buries recovery guidance The release response was invalid. Retry later or pass --version VERSION. implemented verified by exact malformed-release test with parser stderr suppressed
@@ -1,5 +1,5 @@
{
"manifest_id": "ecm_7da021af56cf2eb25489ed7ce494bfe92244e791fa3b5ad5a238a5eb14a23d9a",
"manifest_id": "ecm_125743de92b0cbb08a3cb11ee0d9305f60e5c4fb81152b8b748d348f91f99ee8",
"verifier": {
"id": "rea-managed-conformance",
"version": "1"
@@ -13,7 +13,7 @@
"skill_digests": [
{
"skill_id": "reverse-engineer-anything",
"sha256": "411d5b61e237e3b9b2cb9b3a987d83a36134a2ea1810ddd8d9f695dc05709f5b"
"sha256": "26338313efd5c941e1f3e1f1d35e2605d47749f674c359458e76d5a470b0cbb1"
}
],
"claims": [
+109 -109
View File
@@ -1,165 +1,165 @@
# Windows Ghidra P0
Status: experimental and currently unavailable. The production adapter reports
`unsupported_host` because verified Job Object process ownership, private
runtime DACLs, and reparse-safe path admission are not implemented. Installation
paths or manual MCP registration do not enable operations.
This guide describes the intended P0 boundary and adapter mechanisms. It does
not establish general Windows REA support. Even after the required controls
are implemented, hostile, sensitive, security-decision, and concurrently
mutable targets require separate acceptance.
Status: experimental Windows x64 support for the read-only P0 boundary. The
published package bundles native process, filesystem, and DACL controls. REA
uses them automatically when the analyst selects a Ghidra operation; no
additional permission flag or degraded mode is required.
## Supported boundary
Once the required native controls are implemented, the intended P0 is limited to:
- a Windows x64 host;
- Node.js 22.19+ or 24.11+;
- Windows 10+ x64 with fixed local NTFS target and temporary volumes;
- Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+;
- an operator-installed official Ghidra 12.1.4 distribution;
- a 64-bit full JDK 21;
- an explicit native, non-managed, non-DLL x86-64 PE application; and
- the 22 read-only Ghidra inventory and function-analysis operations.
- the 25 read-only Ghidra inventory, memory, and function-analysis operations.
Hopper, Ghidra GUI state, mutation, process capture, browser/Electron
observation, artifact extraction, and general Windows feature parity are not
implied by this boundary. Managed PE/CLI
inspection remains a separate execution-free provider and is not routed
through Windows Ghidra P0.
Loaded memory reads and file offsets preserve Ghidra's observed source mappings.
PE load-image inspection returns measurements with an explicit unsupported
attestation status; independent format-specific verification currently supports
DOS MZ only.
REA does not install or upgrade Ghidra, Java, Python, npm, Node.js, Hopper, or
another package on Windows. The production adapter uses the packaged Java
`HeadlessScript`; Python and PyGhidra are not prerequisites.
This boundary does not establish general Windows feature parity. Ghidra GUI
state, annotations, other target architectures and formats, and Hopper-only
operations remain unavailable through this provider. Managed PE/CLI inspection
uses its separate execution-free provider.
REA does not install or upgrade Ghidra, Java, Python, npm, Node.js, Hopper, or a
compiler. The adapter uses the packaged Java `HeadlessScript`; Python and
PyGhidra are not prerequisites. Users do not build the native addon.
## Configuration
For installation diagnostics, configure REA, Ghidra, and JDK 21 in PowerShell. Analysis remains blocked:
```powershell
npm install --global rea-agents
$env:GHIDRA_INSTALL_DIR = "C:\tools\ghidra_12.1.4_PUBLIC"
$env:JAVA_HOME = "C:\Program Files\Java\jdk-21"
$env:JAVA_HOME = "C:\tools\jdk-21"
$env:REA_ANALYSIS_PROVIDER = "ghidra"
rea doctor --json
rea providers --json
rea inspect "C:\approved-fixtures\sample.exe" --provider ghidra --format json
rea inspect "C:\fixtures\sample.exe" --provider ghidra --format json
```
`rea doctor` checks the x64 host, exact Ghidra release,
`support\analyzeHeadless.bat`, `java.exe`, `javac.exe`, JDK bitness, and JDK
major version. `rea setup` can configure supported agent integrations and the
bundled REA skill on Windows after approval. It does not install Hopper, Ghidra,
or Java, and configuring an agent does not enable the blocked Ghidra operations.
`rea doctor` distinguishes installation prerequisites from native artifact or
OS failures. It checks the Ghidra release, headless launcher, full JDK, x64
host, and native controls. A missing or mismatched addon requires the matching
Windows x64 package; changing MCP registration cannot supply that artifact.
A filesystem or access failure identifies the failed native constraint.
Other doctor checks, including unconfigured agent integrations, can remain
unready while Ghidra itself is available.
For an MCP client, register the resolved Node entry point and preserve the
three environment variables above. A representative configuration is:
`rea setup` can register supported agent integrations and the bundled skill.
Its existing preview and approval apply to configuration writes. Setup
preserves valid Ghidra and Java settings even when a separate runtime
prerequisite is unavailable.
For MCP, register the resolved Node entry point and the same provider settings:
```json
{
"mcpServers": {
"rea-windows-ghidra-p0": {
"command": "C:\\Program Files\\nodejs\\node.exe",
"args": [
"C:\\Users\\analyst\\AppData\\Roaming\\npm\\node_modules\\rea-agents\\scripts\\rea.mjs",
"mcp"
],
"rea": {
"command": "C:\\tools\\node\\node.exe",
"args": ["C:\\tools\\rea\\scripts\\rea.mjs", "mcp"],
"env": {
"REA_ANALYSIS_PROVIDER": "ghidra",
"GHIDRA_INSTALL_DIR": "C:\\tools\\ghidra_12.1.4_PUBLIC",
"JAVA_HOME": "C:\\Program Files\\Java\\jdk-21"
"JAVA_HOME": "C:\\tools\\jdk-21"
}
}
}
}
```
Resolve the actual global package path on the intended machine; do not copy the
example path blindly. Restart the MCP client after changing its registration.
These paths are examples. Use the actual package location and restart the MCP
client after registration changes. Cold Ghidra import can exceed a client's
short default request timeout; the real verification lane allows the existing
330-second provider startup deadline to complete.
## Target and import identity
## Native authority and target identity
PE parsing records architecture, COFF executable role, and whether the CLI
header data-directory entry is non-empty. Header classification and SHA-256
are read from the same open file handle. Windows admission then rejects:
The verified boundary excludes SUBST aliases and changing drive-letter/DOS-device
namespaces. REA does not claim a separate SUBST detector. Mounted-folder entries
that expose reparse tags fail component admission; broader namespace variants
have not been established by this lane. Requested paths, final handle paths,
volume serials, and file IDs remain separate observations.
- non-PE formats;
- x86, ARM, ARM64, or unknown architectures;
- DLL/shared-library and non-executable image roles;
- managed or incompletely classified PE targets; and
- malformed optional headers or data-directory declarations.
The loader validates package version, ABI, Node-API compatibility, PE machine,
and artifact SHA-256 before loading the package-owned addon. Native failure
reasons remain distinct from a valid installation and an unsupported target.
After admission, REA copies the target into the ephemeral Ghidra runtime and
requires the snapshot digest to match the admitted SHA-256. Ghidra imports only
that snapshot. Before serving a request, the Java bridge requires Ghidra's
`Program.getExecutableSHA256()` observation to match the same digest. A path
replacement that changes bytes therefore fails before Evidence is created.
PE header classification and SHA-256 come from the same open file. The Windows
provider admits native x86-64 PE applications and rejects unsupported roles,
architectures, managed images, and malformed headers. The original selected
source coordinate is preserved for native admission.
This linkage does not establish Windows reparse-point or hostile-path safety.
The current implementation has no handle-based `CreateFileW` authority backend
and no verified no-follow equivalent for every path component.
Admission opens and checks every path component without following a reparse
point. It retains handles, verifies local NTFS semantics, and observes volume
serial, 128-bit file ID, final handle path, requested path, and size. Reparse
paths, alternate streams, ambiguous coordinates, UNC paths, and other
filesystems are rejected with the actual constraint.
## Local transport and lifecycle
The snapshot streams from the admitted source handle on a background worker.
Its digest must match the parsed target digest. Ghidra imports that private,
immutable snapshot, and the bridge requires the imported program SHA-256 to
match before serving operations. Source and snapshot identities remain
separate diagnostic observations. Snapshot cancellation is checked between
64 KiB reads and cleanup waits for worker settlement.
Linux continues to use a mode-restricted Unix socket. Windows uses a Java
listener bound to `127.0.0.1` on an ephemeral port. The bridge atomically
publishes a bounded endpoint record containing only the literal loopback host
and port. The random 256-bit request token remains only in the
ephemeral session descriptor and every request is authenticated.
## Private runtime, transport, and lifecycle
`analyzeHeadless.bat` is invoked through an absolute `cmd.exe` with a fixed
argument sequence, command extensions enabled for the Ghidra script, delayed
expansion disabled, and Node shell execution disabled. Every batch token is
quoted. Paths containing command-interpreter metacharacters are rejected
instead of escaped heuristically.
Runtime creation installs a protected DACL permitting exactly the current user
and SYSTEM. Readback checks the actual owner and ACEs by handle. Descriptors
and snapshots remain locked until owner cleanup. Child files inherit the
private boundary. Analysis runs with the caller's authority; these controls
are not a sandbox for the Ghidra engine or other processes using the same user.
Close, cancellation, timeout, protocol failure, or provider exit removes the
project and runtime root. Windows P0 uses bounded `taskkill /T /F` process-tree
termination. It does not assign Ghidra to a Job Object and cannot make the same
PID-reuse and descendant-ownership claim as the POSIX process-group backend.
Windows uses an authenticated listener bound to `127.0.0.1` on an ephemeral
port. The endpoint record contains only the literal loopback host and port.
The bridge writes a new record and closes its writer before the native reader
can admit it. The reader refuses concurrent writers and verifies its opened
object's private DACL. The random 256-bit bearer token stays in the private,
immutable session descriptor and is redacted from diagnostic output.
## Known security gates
The batch launcher uses an absolute `cmd.exe`, fixed switches, delayed
expansion disabled, and quoted tokens. Command-interpreter metacharacters in
launch paths are unsupported. JVM home and temporary properties use quoted
`JDK_JAVA_OPTIONS`, preserving spaces. `APPDATA` and `LOCALAPPDATA` point into
the private runtime, isolating Ghidra preferences, logs, and caches.
The following remain explicitly unavailable:
- verified current-user-only DACLs for runtime directories, descriptors, logs,
snapshots, and endpoint records;
- a DACL-protected Windows named pipe or equivalent OS-identity-restricted IPC;
- reparse-point-safe, handle-based input and output authority;
- Job Object assignment before child execution and kill-on-close proof;
- general extraction containment and filesystem-sensitive workflows; and
- independent security acceptance for hostile or mutable targets.
Successful symlink creation or ConPTY availability does not satisfy any of
these gates. Inspect the machine-readable report with:
```powershell
npm run probe:windows-capabilities
```
Process creation assigns a suspended child atomically to an owned Job Object.
Membership and kill-on-owner-close policy are verified before resume.
Breakaway is disabled. Only the child's default file owner is normalized;
the caller token stays unchanged. Caller CPU affinity and priority are
preserved. Close, cancellation, timeout, startup failure, and provider failure
terminate the job and verify all members have settled before runtime cleanup.
Cleanup removes admitted objects by handle and unlinks reparse entries without
following their targets. Abrupt owner death kills the job but can leave
private runtime files; crash-time transactional deletion is not claimed.
## Verification
Hosted CI builds, type-checks, runs the curated Windows tests, records the named
host capability report, packs the real npm artifact, installs it in isolation,
and compares the packaged MCP catalog with `TOOL_CONTRACTS`.
The controlled real-engine lane requires the missing native authority and currently remains blocked:
See [native controls](../native/windows/README.md) for the separate artifact
build lane and native boundary checks. Development tarballs without the built
artifact report native controls unavailable; publishing requires the verified
artifact and manifest.
```powershell
$env:GHIDRA_INSTALL_DIR = "C:\tools\ghidra_12.1.4_PUBLIC"
$env:JAVA_HOME = "C:\Program Files\Java\jdk-21"
npm ci
npm run verify:windows-native
npm run verify:ghidra:windows
npm run verify:ghidra:windows:package -- C:\fixtures\installed-rea C:\fixtures\sample.exe
```
The verifier requires the native authority before opening Ghidra. Its intended
checks include a deterministic x86-64 PE fixture, the read-only operation
contract, target/snapshot/import digest linkage, and endpoint, project,
process, and runtime cleanup. The GitHub workflow
accepts only the fixed `real-ghidra-windows` repository-dispatch event against
default-branch `main`, a protected `real-ghidra-windows` environment, and a
self-hosted runner labelled `Windows`, `x64`, and `ghidra-12-1-2`.
The package lane must run with an ordinary, non-elevated user token. It exercises
CLI inspection and every admitted MCP operation, validates named canonical
input/output contracts, checks the source digest stays unchanged, and verifies
runtime cleanup. Use a source-owned fixture, one analysis process at a time,
and a bounded heap for real-provider verification.
Build, package, or adapter-test success does not prove the P0 operation claim.
Real-engine acceptance requires the native controls and the separate
verification lane; broader target and IPC security requirements remain distinct.
The controlled GitHub workflow runs only default-branch code on its protected
self-hosted Windows environment. A separate Linux job builds the matching
native artifact. Hosted Windows CI verifies native controls and packaged
startup separately from real Ghidra acceptance. Broader hostile-target,
concurrently mutable-path, extraction, and IPC-security claims require their
own acceptance and are not implied by this P0 result.
-28
View File
@@ -1,28 +0,0 @@
import eslint from "@eslint/js";
import tseslint from "typescript-eslint";
export default tseslint.config(
{ ignores: ["dist/**", "node_modules/**"] },
eslint.configs.recommended,
...tseslint.configs.strictTypeChecked,
{
files: ["**/*.ts"],
languageOptions: {
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
rules: {
"@typescript-eslint/consistent-type-imports": "error",
"@typescript-eslint/no-confusing-void-expression": "error",
"@typescript-eslint/no-floating-promises": "error",
"@typescript-eslint/no-non-null-assertion": "error",
"@typescript-eslint/no-unnecessary-condition": "error",
"@typescript-eslint/no-unsafe-type-assertion": "error",
"@typescript-eslint/only-throw-error": "error",
"@typescript-eslint/require-await": "error",
"@typescript-eslint/switch-exhaustiveness-check": "error",
},
},
);
+4 -6
View File
@@ -55,17 +55,15 @@ fi
platform="$(uname -s)"
[[ "$platform" == "Darwin" || "$platform" == "Linux" ]] || fail "REA supports macOS and selected 64-bit Linux distributions."
command -v curl >/dev/null 2>&1 || fail "curl is required. Install curl, then rerun this installer."
command -v node >/dev/null 2>&1 || fail "Node.js 22.19+ or 24.11+ is required; install it from https://nodejs.org and retry."
command -v node >/dev/null 2>&1 || fail "Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+ is required; install it from https://nodejs.org and retry."
command -v npm >/dev/null 2>&1 || fail "npm is required; install it with Node.js and retry."
node_version="$(node -p 'process.versions.node' 2>/dev/null || true)"
IFS=. read -r node_major node_minor _node_patch <<<"$node_version"
[[ "$node_major" =~ ^[0-9]+$ && "$node_minor" =~ ^[0-9]+$ ]] || fail "the active Node.js version could not be read. Check that node works and is on PATH, then retry."
if ! ((node_major == 22 && node_minor >= 19 || node_major >= 24)); then
fail "Node.js $node_version is unsupported; use Node.js 22.19+ or 24.11+."
fi
if ((node_major == 24 && node_minor < 11)); then
fail "Node.js $node_version is unsupported; use Node.js 24.11 or newer."
if ! [[ "$_node_patch" =~ ^[0-9]+(\+[0-9A-Za-z.-]+)?$ ]] ||
! ((node_major == 22 && node_minor >= 19 || node_major == 24 && node_minor >= 11 || node_major >= 26)); then
fail "Node.js $node_version is unsupported; use Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+."
fi
if [[ -n "$version" ]]; then
+1 -13
View File
@@ -1,21 +1,9 @@
{
"$schema": "./node_modules/knip/schema.json",
"entry": [
"src/main.ts",
"src/cli.ts",
"src/contracts/errorSchemas.ts",
"scripts/run-development-tests.mjs"
],
"entry": ["src/main.ts", "src/cli.ts", "src/contracts/errorSchemas.ts"],
"project": ["src/**/*.ts", "tests/**/*.ts", "scripts/**/*.mjs"],
"ignoreDependencies": ["electron"],
"ignoreBinaries": ["ps"],
"ignoreExportsUsedInFile": true,
"ignoreIssues": {
"src/domain/mobileApplicationInvestigation.ts": ["types"],
"src/domain/objcSwiftMetadata.ts": ["types"],
"src/domain/interfaceBuilderGraph.ts": ["types"],
"src/domain/nativeInvestigationGraph.ts": ["types"]
},
"rules": {
"files": "error",
"dependencies": "error",
+102
View File
@@ -0,0 +1,102 @@
# Windows native controls
REA ships one Windows x64 Node-API 8 addon. Users do not compile it or install
another runtime. Ghidra and a full JDK remain bring-your-own prerequisites.
The addon uses Windows 10+ APIs and admits fixed local NTFS volumes only.
The package owns the artifact path. The loader checks the package version,
ABI, Node-API compatibility, PE architecture, and SHA-256 before loading it.
There is no environment override for loading an arbitrary native module.
## Build
The artifact lane requires Linux, MinGW-w64 `x86_64-w64-mingw32-g++`,
`x86_64-w64-mingw32-dlltool`, and `tar`. It never installs these commands.
Node-API headers are reused from the build cache or downloaded from the
pinned official Node release with its published SHA-256 checked.
```sh
npm run build:windows-native
npm run verify:windows-native:artifact
npm pack
```
`build/` is ignored by Git. The npm file inventory includes only the addon and
its manifest. Release CI builds both, and `prepublishOnly` rejects a missing,
stale, mismatched, or wrong-architecture artifact. A development tarball built
without this lane reports Windows native controls as unavailable.
## Boundaries
- Opaque Node objects carry a native type tag, resource kind, and closed state.
A pathname, serialized object, or forged handle cannot grant authority.
- Input admission opens every component with `OPEN_REPARSE_POINT`, verifies
the actual NTFS object, and retains handles that deny replacement and source
writing. An admitted child keeps each ancestor nonempty; ancestor handles
permit unrelated writes while NTFS rejects in-place reparse conversion. Volume serial, 128-bit file ID, final handle path,
requested path, size, and digest observations are preserved separately.
- New runtime roots and private child objects are created relative to admitted
parent handles with `NtCreateFile`. A protected DACL and current-user owner
are installed at creation. Readback permits exactly the current user and SYSTEM. Child
files inherit this boundary; private files are also checked by handle.
- Snapshots stream through a 64 KiB buffer on a Node async worker. Cancellation
is checked between reads, cleanup waits for settlement, and the digest
commits to the bytes written. Descriptor and snapshot handles remain held
until runtime cleanup.
Snapshot ownership is single-flight per runtime: an overlapping request fails
with `ERROR_BUSY` before acquiring cancellation ownership. The TypeScript owner
records only the accepted promise and abort listener; aborting a rejected copy
must not cancel the active copy.
- `PROC_THREAD_ATTRIBUTE_JOB_LIST` assigns a suspended child atomically to an
unnamed, non-inherited Job Object. Membership and kill-on-close policy are
checked before resume. Breakaway is disabled, and cleanup waits for all
job members and captured output, including detached descendants.
- Only the suspended child's default file owner is normalized. Caller token
privileges and ownership remain unchanged. Caller CPU affinity and process
priority are preserved in the child. Environment names are sorted and
deduplicated using Windows ordinal comparison, preserving their native Unicode
semantics and caller-selected values.
- Cleanup walks locked directory objects, removes files by handle, and unlinks
reparse entries without traversing their targets. Normal close, cancellation,
startup failure, and timeout release provider resources. Abrupt owner death
kills the owned job; it can leave private runtime files for later operator
cleanup and does not claim transactional deletion after a crash.
Windows failures retain their constraint, requested coordinate, Win32 code,
and system message. Unsupported filesystems and reparse paths are distinct
from OS access denial and missing packaged controls.
The bearer-token descriptor remains under its immutable private lease until
`runtime_close` on Windows; POSIX removes the descriptor after the bridge reads
it. Job ownership guarantees process termination on owner death, not deletion
of private files after a crash. SUBST drive aliases and changing DOS-device
namespaces are outside the verified P0 scope and are not detected as a separate
alias policy. Mounted-folder paths that report a reparse tag are rejected by
component admission; broader namespace variants remain unverified. Preserve
requested and final handle coordinates rather than treating them as one identity.
## Real verification
```powershell
npm run verify:windows-native
npm run verify:ghidra:windows
```
The native lane checks DACL readback independently, source write/replacement
rejection, unrelated sibling renames, reparse rejection, immutable snapshots,
asynchronous cancellation, cleanup containment,
descendant termination, unrelated-process preservation, normal exit, owner
close, and forced owner exit. An optional independently built
`tests/fixtures/windows/processBoundary.cc` executable adds breakaway and
caller/child token observations and an in-place ancestor reparse attempt:
```powershell
node scripts/verify-windows-native.mjs . C:\fixtures\process-boundary.exe
```
`nonAdminRunner.cc` is a test-only launcher for an elevated development shell.
It duplicates an existing non-elevated Explorer token belonging to the same
user, creates private temporary window-station objects, and launches the test
inside a kill-on-close fixture job. It does not create accounts, modify host
policy, or change the caller's token. A real-provider claim must additionally
verify the packaged CLI and MCP on that ordinary-user token.
+123
View File
@@ -0,0 +1,123 @@
#include "authority.hpp"
namespace rea {
static const napi_type_tag RESOURCE_TAG = {0x45fcbf0b49e84fe3ULL, 0x9e3e5074130de843ULL};
void check(napi_status status) {
if (status != napi_ok) throw Failure("Invalid native boundary value", L"", ERROR_INVALID_PARAMETER);
}
napi_value object(napi_env env) { napi_value value; check(napi_create_object(env, &value)); return value; }
napi_value null(napi_env env) { napi_value value; check(napi_get_null(env, &value)); return value; }
napi_value string(napi_env env, const std::string& text) {
napi_value value; check(napi_create_string_utf8(env, text.data(), text.size(), &value)); return value;
}
napi_value string(napi_env env, const std::wstring& text) {
static_assert(sizeof(wchar_t) == sizeof(char16_t));
napi_value value;
check(napi_create_string_utf16(env, reinterpret_cast<const char16_t*>(text.data()), text.size(), &value));
return value;
}
napi_value number(napi_env env, double numeric) {
napi_value value; check(napi_create_double(env, numeric, &value)); return value;
}
napi_value boolean(napi_env env, bool flag) {
napi_value value; check(napi_get_boolean(env, flag, &value)); return value;
}
void set(napi_env env, napi_value target, const char* key, napi_value value) {
check(napi_set_named_property(env, target, key, value));
}
std::wstring wide(napi_env env, napi_value value) {
size_t size = 0;
check(napi_get_value_string_utf16(env, value, nullptr, 0, &size));
require(size <= 32767, "Windows value exceeds the native string limit", L"", ERROR_INVALID_PARAMETER);
std::vector<char16_t> buffer(size + 1);
check(napi_get_value_string_utf16(env, value, buffer.data(), buffer.size(), &size));
std::wstring result(reinterpret_cast<const wchar_t*>(buffer.data()), size);
require(result.find(L'\0') == std::wstring::npos, "Windows value contains NUL", L"", ERROR_INVALID_PARAMETER);
return result;
}
double numeric(napi_env env, napi_value value) {
double result; check(napi_get_value_double(env, value, &result)); return result;
}
std::vector<napi_value> array(napi_env env, napi_value value) {
bool valid; check(napi_is_array(env, value, &valid));
require(valid, "Native arguments must be an array", L"", ERROR_INVALID_PARAMETER);
uint32_t length; check(napi_get_array_length(env, value, &length));
std::vector<napi_value> result(length);
for (uint32_t index = 0; index < length; ++index)
check(napi_get_element(env, value, index, &result[index]));
return result;
}
static void finalize(napi_env, void* data, void*) { delete static_cast<Resource*>(data); }
napi_value wrap(napi_env env, std::unique_ptr<Resource> value) {
auto result = object(env);
check(napi_type_tag_object(env, result, &RESOURCE_TAG));
check(napi_wrap(env, result, value.get(), finalize, nullptr, nullptr));
value.release();
return result;
}
Resource& resource(napi_env env, napi_value value, Kind kind) {
bool tagged = false;
check(napi_check_object_type_tag(env, value, &RESOURCE_TAG, &tagged));
require(tagged, "Native handle does not belong to REA", L"", ERROR_INVALID_HANDLE);
void* pointer = nullptr; check(napi_unwrap(env, value, &pointer));
auto& result = *static_cast<Resource*>(pointer);
require(result.kind == kind && !result.closed, "Native handle is closed or has the wrong kind", L"", ERROR_INVALID_HANDLE);
return result;
}
napi_value failureValue(napi_env env, const Failure& failure) {
wchar_t* message = nullptr;
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, failure.win32, 0, reinterpret_cast<wchar_t*>(&message), 0, nullptr);
std::wstring detail = message == nullptr ? L"" : message;
if (message != nullptr) LocalFree(message);
const std::wstring constraint(failure.constraint.begin(), failure.constraint.end());
auto text = string(env, constraint + (failure.path.empty() ? L"" : L" [" + failure.path + L"]") +
L" (Win32 " + std::to_wstring(failure.win32) + L"): " + detail);
napi_value error; napi_create_error(env, nullptr, text, &error);
const char* code = failure.win32 == ERROR_FILE_NOT_FOUND || failure.win32 == ERROR_PATH_NOT_FOUND ? "ENOENT"
: failure.win32 == ERROR_ACCESS_DENIED ? "EACCES" : "ERR_REA_WINDOWS_NATIVE";
set(env, error, "code", string(env, std::string(code)));
set(env, error, "constraint", string(env, failure.constraint));
set(env, error, "requestedPath", string(env, failure.path));
set(env, error, "win32Code", number(env, failure.win32));
set(env, error, "win32Message", string(env, detail));
return error;
}
static napi_value call(napi_env env, napi_callback_info info) {
try {
std::array<napi_value, 2> args;
size_t count = args.size();
check(napi_get_cb_info(env, info, &count, args.data(), nullptr, nullptr));
require(count == 2, "Native call requires operation and arguments", L"", ERROR_INVALID_PARAMETER);
const auto operation = wide(env, args[0]);
const auto values = array(env, args[1]);
if (operation == L"inspect") {
require(values.empty(), "Inspect takes no arguments", L"", ERROR_INVALID_PARAMETER);
return inspect(env);
}
if (operation.rfind(L"process_", 0) == 0) return processCall(env, operation, values);
return filesystemCall(env, operation, values);
} catch (const Failure& failure) {
auto error = failureValue(env, failure);
napi_throw(env, error);
return nullptr;
} catch (const std::exception& failure) {
napi_throw_error(env, "ERR_REA_WINDOWS_NATIVE", failure.what());
return nullptr;
}
}
static napi_value initialize(napi_env env, napi_value exports) {
napi_value function;
if (napi_create_function(env, "call", NAPI_AUTO_LENGTH, call, nullptr, &function) != napi_ok) return nullptr;
if (napi_set_named_property(env, exports, "call", function) != napi_ok) return nullptr;
return exports;
}
} // namespace rea
NAPI_MODULE(NODE_GYP_MODULE_NAME, rea::initialize)
+120
View File
@@ -0,0 +1,120 @@
#pragma once
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#include <aclapi.h>
#include <bcrypt.h>
#include <node_api.h>
#include <algorithm>
#include <array>
#include <atomic>
#include <cstdint>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
namespace rea {
struct Failure : std::runtime_error {
DWORD win32;
std::wstring path;
std::string constraint;
Failure(std::string constraint, std::wstring path = L"", DWORD code = GetLastError())
: std::runtime_error(constraint), win32(code), path(std::move(path)),
constraint(std::move(constraint)) {}
};
inline void require(bool condition, const char* constraint, const std::wstring& path = L"") {
if (!condition) {
const auto code = GetLastError();
throw Failure(constraint, path, code);
}
}
inline void require(bool condition, const char* constraint, const std::wstring& path, DWORD code) {
if (!condition) throw Failure(constraint, path, code);
}
class Handle {
HANDLE value_ = INVALID_HANDLE_VALUE;
public:
Handle() = default;
explicit Handle(HANDLE value) : value_(value) {}
~Handle() { reset(); }
Handle(const Handle&) = delete;
Handle& operator=(const Handle&) = delete;
Handle(Handle&& other) noexcept : value_(other.release()) {}
Handle& operator=(Handle&& other) noexcept { reset(other.release()); return *this; }
HANDLE get() const { return value_; }
bool valid() const { return value_ != INVALID_HANDLE_VALUE && value_ != nullptr; }
HANDLE release() { return std::exchange(value_, INVALID_HANDLE_VALUE); }
void reset(HANDLE next = INVALID_HANDLE_VALUE) {
if (valid()) CloseHandle(value_);
value_ = next;
}
};
enum class Kind { File, Runtime, Process };
struct Resource {
const Kind kind;
bool closed = false;
explicit Resource(Kind value) : kind(value) {}
virtual ~Resource() = default;
};
struct File : Resource {
std::wstring requestedPath;
std::wstring path;
std::vector<Handle> handles;
explicit File(std::wstring path) : Resource(Kind::File), requestedPath(path), path(std::move(path)) {}
HANDLE get() const { return handles.back().get(); }
};
struct Runtime : Resource {
std::wstring path;
std::vector<Handle> parents;
Handle directory;
std::vector<Handle> immutableFiles;
// Main-thread admission is single-flight; only the accepted copy owns the
// atomic cancellation flag consumed by its async worker. ERROR_BUSY rejects
// another copy before it can reset that flag or replace pending ownership.
bool snapshotPending = false;
std::atomic_bool snapshotCancelled{false};
Runtime() : Resource(Kind::Runtime) {}
};
struct Process : Resource {
Handle job, process, stdoutRead, stderrRead;
DWORD pid = 0;
Process() : Resource(Kind::Process) {}
};
void check(napi_status status);
napi_value failureValue(napi_env env, const Failure& failure);
napi_value object(napi_env env);
napi_value string(napi_env env, const std::string& value);
napi_value string(napi_env env, const std::wstring& value);
napi_value number(napi_env env, double value);
napi_value boolean(napi_env env, bool value);
napi_value null(napi_env env);
void set(napi_env env, napi_value object, const char* key, napi_value value);
std::wstring wide(napi_env env, napi_value value);
double numeric(napi_env env, napi_value value);
std::vector<napi_value> array(napi_env env, napi_value value);
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);
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);
napi_value filesystemCall(napi_env env, const std::wstring& operation,
const std::vector<napi_value>& args);
std::unique_ptr<Process> spawnProcess(const std::wstring& command, const std::wstring& commandLine,
const std::wstring& cwd, const std::vector<std::wstring>& environment);
napi_value processCall(napi_env env, const std::wstring& operation,
const std::vector<napi_value>& args);
napi_value inspect(napi_env env);
} // namespace rea
+531
View File
@@ -0,0 +1,531 @@
#include "authority.hpp"
#include <sddl.h>
#include <winternl.h>
namespace rea {
static std::wstring hex(const unsigned char* bytes, size_t count) {
constexpr wchar_t digits[] = L"0123456789abcdef";
std::wstring result;
for (size_t index = 0; index < count; ++index) {
result += digits[bytes[index] >> 4]; result += digits[bytes[index] & 15];
}
return result;
}
static std::wstring localPath(std::wstring path) {
if (path.rfind(L"\\\\?\\", 0) == 0) path.erase(0, 4);
require(path.size() >= 3 && path[1] == L':' && path[2] == L'\\' &&
((path[0] >= L'A' && path[0] <= L'Z') || (path[0] >= L'a' && path[0] <= L'z')),
"Only absolute local NTFS drive paths are supported", path, ERROR_NOT_SUPPORTED);
require(path.find(L'/', 0) == std::wstring::npos && path.find(L':', 2) == std::wstring::npos,
"Alternate streams and non-local path syntax are unsupported", path, ERROR_NOT_SUPPORTED);
require(GetDriveTypeW(path.substr(0, 3).c_str()) == DRIVE_FIXED,
"Only fixed local NTFS volumes are supported", path, ERROR_NOT_SUPPORTED);
if (path.size() > 3 && path.back() == L'\\') path.pop_back();
require(path.size() == 3 || path.back() != L'\\', "Repeated path separators are unsupported", path, ERROR_NOT_SUPPORTED);
size_t begin = 3;
while (begin < path.size()) {
const auto end = path.find(L'\\', begin);
const auto component = path.substr(begin, end == std::wstring::npos ? end : end - begin);
require(!component.empty() && component != L"." && component != L".." &&
component.back() != L'.' && component.back() != L' ',
"Ambiguous Windows path component is unsupported", path, ERROR_NOT_SUPPORTED);
if (end == std::wstring::npos) break;
begin = end + 1;
}
return path;
}
static Handle openComponent(const std::wstring& path, DWORD access, bool directory, DWORD sharing = FILE_SHARE_READ) {
// Attribute-only opens do not participate in Windows share-access checks.
// Directory guards need FILE_LIST_DIRECTORY to prevent replacement and
// in-place reparse conversion while descendant paths are being consumed.
Handle handle(CreateFileW((L"\\\\?\\" + path).c_str(), access | FILE_READ_ATTRIBUTES | READ_CONTROL |
(directory ? FILE_LIST_DIRECTORY : 0),
sharing, nullptr, OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, nullptr));
require(handle.valid(), "Open Windows path component failed", path);
FILE_ATTRIBUTE_TAG_INFO info{};
require(GetFileInformationByHandleEx(handle.get(), FileAttributeTagInfo, &info, sizeof(info)),
"Read Windows path attributes failed", path);
if ((info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0)
throw Failure("Reparse path component is unsupported (tag " + std::to_string(info.ReparseTag) + ")",
path, ERROR_NOT_SUPPORTED);
require(((info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) == directory,
directory ? "Expected a directory path component" : "Target is not a regular file", path,
directory ? ERROR_PATH_NOT_FOUND : ERROR_DIRECTORY);
require(GetFileType(handle.get()) == FILE_TYPE_DISK, "Windows object is not a disk file", path, ERROR_NOT_SUPPORTED);
return handle;
}
std::unique_ptr<File> openFile(const std::wstring& requested, DWORD access, bool directory) {
auto result = std::make_unique<File>(localPath(requested));
result->requestedPath = requested;
const auto& path = result->path;
require(directory || path.size() > 3, "Target is not a regular file", requested, ERROR_DIRECTORY);
result->handles.push_back(openComponent(path.substr(0, 3), 0, true));
wchar_t filesystem[64]{};
DWORD flags = 0;
require(GetVolumeInformationByHandleW(result->handles.front().get(), nullptr, 0, nullptr, nullptr,
&flags, filesystem, 64), "Read volume semantics failed", path);
require(std::wstring(filesystem) == L"NTFS" && (flags & FILE_PERSISTENT_ACLS) != 0,
"Backing volume must be NTFS with persistent ACLs", path, ERROR_NOT_SUPPORTED);
size_t offset = 3;
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);
// 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.
// Independent evidence: tests/fixtures/windows/processBoundary.cc attempts
// FSCTL_SET_REPARSE_POINT on the nonempty pinned ancestor and observes denial.
// SUBST aliases and mounted-folder/reparse namespace variants are outside
// the admitted P0 evidence; requested and final handle paths remain distinct.
const auto parentPath = offset == 3 ? path.substr(0, 3) : path.substr(0, offset - 1);
result->handles.back() = openComponent(parentPath, 0, true, FILE_SHARE_READ | FILE_SHARE_WRITE);
result->handles.push_back(std::move(child));
if (final) break;
offset = end + 1;
}
return result;
}
napi_value identity(napi_env env, HANDLE handle, const std::wstring& path) {
FILE_ID_INFO info{};
require(GetFileInformationByHandleEx(handle, FileIdInfo, &info, sizeof(info)),
"Stable 128-bit Windows file identity is unavailable", path);
std::array<wchar_t, 32768> finalPath;
const auto length = GetFinalPathNameByHandleW(handle, finalPath.data(), finalPath.size(), FILE_NAME_NORMALIZED);
require(length > 0 && length < finalPath.size(), "Read final handle path failed", path);
LARGE_INTEGER size{};
FILE_STANDARD_INFO standard{};
require(GetFileInformationByHandleEx(handle, FileStandardInfo, &standard, sizeof(standard)),
"Read handle metadata failed", path);
size = standard.EndOfFile;
require(size.QuadPart >= 0 && size.QuadPart <= 9007199254740991LL, "File size exceeds exact numeric representation", path,
ERROR_NOT_SUPPORTED);
auto result = object(env);
set(env, result, "requestedPath", string(env, path));
set(env, result, "finalPath", string(env, std::wstring(finalPath.data(), length)));
set(env, result, "filesystem", string(env, std::string("NTFS")));
std::array<unsigned char, 8> serial;
for (size_t index = 0; index < serial.size(); ++index)
serial[index] = static_cast<unsigned char>(info.VolumeSerialNumber >> ((7 - index) * 8));
set(env, result, "volumeSerial", string(env, hex(serial.data(), serial.size())));
set(env, result, "fileId", string(env, hex(info.FileId.Identifier, 16)));
set(env, result, "size", number(env, static_cast<double>(size.QuadPart)));
set(env, result, "directory", boolean(env, standard.Directory != FALSE));
return result;
}
struct Security {
std::vector<unsigned char> user;
std::array<unsigned char, SECURITY_MAX_SID_SIZE> system{};
std::vector<unsigned char> acl;
SECURITY_DESCRIPTOR descriptor{};
PSID userSid() const { return reinterpret_cast<const TOKEN_USER*>(user.data())->User.Sid; }
Security() {
Handle token;
HANDLE raw;
require(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &raw), "Read current user token failed");
token.reset(raw);
DWORD size = 0;
GetTokenInformation(token.get(), TokenUser, nullptr, 0, &size);
user.resize(size);
require(GetTokenInformation(token.get(), TokenUser, user.data(), size, &size), "Read current user SID failed");
DWORD systemSize = system.size();
require(CreateWellKnownSid(WinLocalSystemSid, nullptr, system.data(), &systemSize), "Create SYSTEM SID failed");
acl.resize(sizeof(ACL) + 2 * (sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)) + GetLengthSid(userSid()) + systemSize);
auto access = reinterpret_cast<PACL>(acl.data());
require(InitializeAcl(access, acl.size(), ACL_REVISION), "Initialize private DACL failed");
for (PSID sid : {userSid(), static_cast<PSID>(system.data())})
require(AddAccessAllowedAceEx(access, ACL_REVISION, OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE,
FILE_ALL_ACCESS, sid), "Populate private DACL failed");
require(InitializeSecurityDescriptor(&descriptor, SECURITY_DESCRIPTOR_REVISION) &&
SetSecurityDescriptorOwner(&descriptor, userSid(), FALSE) &&
SetSecurityDescriptorDacl(&descriptor, TRUE, access, FALSE) &&
SetSecurityDescriptorControl(&descriptor, SE_DACL_PROTECTED, SE_DACL_PROTECTED),
"Create protected security descriptor failed");
}
};
static Handle createRelative(HANDLE parent, const std::wstring& name, DWORD access, bool directory,
Security& security, const std::wstring& path) {
require(!name.empty() && name.find_first_of(L"\\/:\"<>|?*") == std::wstring::npos && name.size() < 32768,
"Private object 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, &security.descriptor);
IO_STATUS_BLOCK observation{};
HANDLE raw = INVALID_HANDLE_VALUE;
const auto status = NtCreateFile(&raw, access | SYNCHRONIZE, &attributes, &observation, nullptr,
FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_CREATE,
FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_REPARSE_POINT |
(directory ? FILE_DIRECTORY_FILE : FILE_NON_DIRECTORY_FILE), nullptr, 0);
if (status < 0) throw Failure("Create private object relative to its admitted parent failed", path,
RtlNtStatusToDosError(status));
Handle result(raw);
require(result.valid() && observation.Information == FILE_CREATED,
"Private creation did not return a new object handle", path, ERROR_ACCESS_DENIED);
return result;
}
static void verifyPrivate(HANDLE handle, const std::wstring& path, bool root) {
Security expected;
PSID owner = nullptr;
PACL acl = nullptr;
PSECURITY_DESCRIPTOR raw = nullptr;
const DWORD code = GetSecurityInfo(handle, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
&owner, nullptr, &acl, nullptr, &raw);
if (code != ERROR_SUCCESS) throw Failure("Read private DACL by handle failed", path, code);
const auto descriptor = std::unique_ptr<void, decltype(&LocalFree)>(raw, LocalFree);
require(owner != nullptr && EqualSid(owner, expected.userSid()), "Private object owner is not the current user", path,
ERROR_ACCESS_DENIED);
SECURITY_DESCRIPTOR_CONTROL control;
DWORD revision;
require(GetSecurityDescriptorControl(raw, &control, &revision), "Read DACL control flags failed", path);
require(acl != nullptr && (control & SE_DACL_PRESENT) != 0 && (!root || (control & SE_DACL_PROTECTED) != 0),
"Private object requires a present protected DACL", path, ERROR_ACCESS_DENIED);
require(acl->AceCount == 2, "Private DACL contains unexpected trustees", path, ERROR_ACCESS_DENIED);
bool user = false, system = false;
for (DWORD index = 0; index < acl->AceCount; ++index) {
void* rawAce;
require(GetAce(acl, index, &rawAce), "Read private DACL entry failed", path);
const auto ace = static_cast<ACCESS_ALLOWED_ACE*>(rawAce);
require(ace->Header.AceType == ACCESS_ALLOWED_ACE_TYPE && ace->Mask == FILE_ALL_ACCESS &&
(ace->Header.AceFlags & INHERIT_ONLY_ACE) == 0 &&
(!root || (ace->Header.AceFlags & (OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE)) ==
(OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE)),
"Private DACL contains unsupported rights or ACE type", path, ERROR_ACCESS_DENIED);
PSID sid = const_cast<DWORD*>(&ace->SidStart);
if (EqualSid(sid, expected.userSid())) user = true;
else if (EqualSid(sid, expected.system.data())) system = true;
else throw Failure("Private DACL permits an unrelated principal", path, ERROR_ACCESS_DENIED);
}
require(user && system, "Private DACL must allow only current user and SYSTEM", path, ERROR_ACCESS_DENIED);
}
std::unique_ptr<Runtime> createRuntime(const std::wstring& parentPath, const std::wstring& prefix) {
auto parent = openFile(parentPath, 0, true);
require(!prefix.empty() && prefix.find_first_of(L"\\/:\"<>|?*") == std::wstring::npos,
"Runtime prefix must be one filename component", parentPath, ERROR_INVALID_PARAMETER);
std::array<unsigned char, 16> random;
require(BCryptGenRandom(nullptr, random.data(), random.size(), BCRYPT_USE_SYSTEM_PREFERRED_RNG) == 0,
"Generate runtime identity failed", parentPath, ERROR_GEN_FAILURE);
auto result = std::make_unique<Runtime>();
result->path = parent->path + L"\\" + prefix + hex(random.data(), random.size());
Security security;
result->directory = createRelative(parent->get(), prefix + hex(random.data(), random.size()),
DELETE | FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES | READ_CONTROL,
true, security, result->path);
try {
verifyPrivate(result->directory.get(), result->path, true);
// The owned child pins the parent nonempty before write sharing is relaxed.
parent->handles.back() = openComponent(parent->path, 0, true, FILE_SHARE_READ | FILE_SHARE_WRITE);
result->parents = std::move(parent->handles);
} catch (...) {
FILE_DISPOSITION_INFO deletion{TRUE};
SetFileInformationByHandle(result->directory.get(), FileDispositionInfo, &deletion, sizeof(deletion));
throw;
}
return result;
}
static std::wstring relativePath(Runtime& root, const std::wstring& relative) {
require(!relative.empty() && relative[0] != L'\\' && relative.find(L':') == std::wstring::npos,
"Runtime coordinate must be a relative path", relative, ERROR_INVALID_PARAMETER);
return localPath(root.path + L"\\" + relative);
}
static std::unique_ptr<File> runtimeDirectory(Runtime& root, const std::wstring& path) {
auto result = std::make_unique<File>(path);
HANDLE duplicate;
require(DuplicateHandle(GetCurrentProcess(), root.directory.get(), GetCurrentProcess(), &duplicate, 0, FALSE,
DUPLICATE_SAME_ACCESS), "Duplicate private directory handle failed", path);
result->handles.emplace_back(duplicate);
size_t offset = root.path.size() + 1;
while (offset < path.size()) {
const auto end = path.find(L'\\', offset);
result->handles.push_back(openComponent(path.substr(0, end), 0, true));
if (end == std::wstring::npos) break;
offset = end + 1;
}
return result;
}
static void directory(Runtime& root, const std::wstring& relative) {
const auto path = relativePath(root, relative);
const auto parentPath = path.substr(0, path.find_last_of(L'\\'));
auto parent = runtimeDirectory(root, parentPath);
verifyPrivate(parent->get(), parentPath, parentPath == root.path);
Security security;
try {
auto created = createRelative(parent->get(), path.substr(path.find_last_of(L'\\') + 1),
FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES | READ_CONTROL,
true, security, path);
verifyPrivate(created.get(), path, false);
} catch (const Failure& failure) {
if (failure.win32 != ERROR_ALREADY_EXISTS && failure.win32 != ERROR_FILE_EXISTS) throw;
auto existing = runtimeDirectory(root, path);
verifyPrivate(existing->get(), path, false);
}
}
static Handle createPrivateFile(Runtime& root, const std::wstring& relative) {
const auto path = relativePath(root, relative);
const auto parentPath = path.substr(0, path.find_last_of(L'\\'));
auto parent = runtimeDirectory(root, parentPath);
verifyPrivate(parent->get(), parentPath, parentPath == root.path);
Security security;
auto file = createRelative(parent->get(), path.substr(path.find_last_of(L'\\') + 1),
GENERIC_WRITE | GENERIC_READ | READ_CONTROL, false, security, path);
verifyPrivate(file.get(), path, false);
return file;
}
static void writeBytes(HANDLE file, const void* bytes, DWORD count, const std::wstring& path) {
DWORD written;
require(WriteFile(file, bytes, count, &written, nullptr) && written == count, "Write private file failed", path);
}
static void dispose(HANDLE handle, const std::wstring& path) {
FILE_BASIC_INFO info{};
require(GetFileInformationByHandleEx(handle, FileBasicInfo, &info, sizeof(info)), "Read cleanup attributes failed", path);
if ((info.FileAttributes & FILE_ATTRIBUTE_READONLY) != 0) {
info.FileAttributes &= ~FILE_ATTRIBUTE_READONLY;
require(SetFileInformationByHandle(handle, FileBasicInfo, &info, sizeof(info)), "Clear owned readonly attribute failed", path);
}
FILE_DISPOSITION_INFO deletion{TRUE};
require(SetFileInformationByHandle(handle, FileDispositionInfo, &deletion, sizeof(deletion)), "Delete owned object by handle failed", path);
}
void closeRuntime(Runtime& root) {
if (root.closed) return;
// Windows keeps the bearer descriptor and snapshot leases until this owner
// cleanup. POSIX removes its consumed descriptor earlier. Abrupt owner death
// closes process jobs but cannot run this walk, so private files can remain.
root.immutableFiles.clear();
struct ReleaseRuntime {
Runtime& root;
~ReleaseRuntime() { root.directory.reset(); root.parents.clear(); root.closed = true; }
} release{root};
// Each traversed directory stays locked against replacement. Reparse entries
// are unlinked as objects; their targets are never enumerated or deleted.
struct Frame {
Handle directory;
HANDLE search = INVALID_HANDLE_VALUE;
std::wstring path;
WIN32_FIND_DATAW next{};
bool pending = false;
Frame(Handle handle, std::wstring path) : directory(std::move(handle)), path(std::move(path)) {
search = FindFirstFileExW((L"\\\\?\\" + this->path + L"\\*").c_str(), FindExInfoBasic, &next,
FindExSearchNameMatch, nullptr, 0);
pending = search != INVALID_HANDLE_VALUE;
require(pending || GetLastError() == ERROR_FILE_NOT_FOUND, "Enumerate runtime cleanup failed", this->path);
}
~Frame() { if (search != INVALID_HANDLE_VALUE) FindClose(search); }
};
std::vector<std::unique_ptr<Frame>> frames;
HANDLE duplicate;
require(DuplicateHandle(GetCurrentProcess(), root.directory.get(), GetCurrentProcess(), &duplicate, 0, FALSE,
DUPLICATE_SAME_ACCESS), "Duplicate runtime cleanup handle failed", root.path);
frames.push_back(std::make_unique<Frame>(Handle(duplicate), root.path));
while (!frames.empty()) {
auto& frame = *frames.back();
if (!frame.pending) {
if (frame.search != INVALID_HANDLE_VALUE) { FindClose(frame.search); frame.search = INVALID_HANDLE_VALUE; }
dispose(frame.directory.get(), frame.path);
frames.pop_back();
continue;
}
const auto name = std::wstring(frame.next.cFileName);
frame.pending = FindNextFileW(frame.search, &frame.next) != FALSE;
require(frame.pending || GetLastError() == ERROR_NO_MORE_FILES, "Continue runtime cleanup enumeration failed", frame.path);
if (name == L"." || name == L"..") continue;
const auto path = frame.path + L"\\" + name;
Handle child(CreateFileW((L"\\\\?\\" + path).c_str(), DELETE | GENERIC_READ | FILE_WRITE_ATTRIBUTES,
FILE_SHARE_READ, nullptr, OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, nullptr));
require(child.valid(), "Open owned cleanup object failed", path);
FILE_ATTRIBUTE_TAG_INFO info{};
require(GetFileInformationByHandleEx(child.get(), FileAttributeTagInfo, &info, sizeof(info)), "Read cleanup object tag failed", path);
if ((info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 && (info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0)
frames.push_back(std::make_unique<Frame>(std::move(child), path));
else dispose(child.get(), path);
}
}
struct SnapshotWork {
napi_env env;
napi_async_work work = nullptr;
napi_deferred deferred = nullptr;
napi_ref rootReference = nullptr;
Runtime* root;
std::unique_ptr<File> source;
Handle destination;
std::wstring path;
std::wstring digest;
std::unique_ptr<Failure> failure;
SnapshotWork(napi_env env, Runtime& root) : env(env), root(&root) {}
};
static void copySnapshot(napi_env, void* pointer) {
auto& work = *static_cast<SnapshotWork*>(pointer);
try {
BCRYPT_ALG_HANDLE algorithm = nullptr;
require(BCryptOpenAlgorithmProvider(&algorithm, BCRYPT_SHA256_ALGORITHM, nullptr, 0) == 0,
"Initialize snapshot SHA-256 failed", work.source->path, ERROR_GEN_FAILURE);
struct Algorithm { BCRYPT_ALG_HANDLE handle; ~Algorithm() { BCryptCloseAlgorithmProvider(handle, 0); } } owner{algorithm};
BCRYPT_HASH_HANDLE hash = nullptr;
require(BCryptCreateHash(algorithm, &hash, nullptr, 0, nullptr, 0, 0) == 0,
"Create snapshot SHA-256 state failed", work.source->path, ERROR_GEN_FAILURE);
struct Hash { BCRYPT_HASH_HANDLE handle; ~Hash() { BCryptDestroyHash(handle); } } hashOwner{hash};
std::array<unsigned char, 65536> buffer;
while (true) {
require(!work.root->snapshotCancelled.load(), "Admitted snapshot was cancelled", work.path, ERROR_OPERATION_ABORTED);
DWORD count;
require(ReadFile(work.source->get(), buffer.data(), buffer.size(), &count, nullptr),
"Read admitted source handle failed", work.source->path);
if (count == 0) break;
writeBytes(work.destination.get(), buffer.data(), count, work.path);
require(BCryptHashData(hash, buffer.data(), count, 0) == 0,
"Hash admitted snapshot bytes failed", work.source->path, ERROR_GEN_FAILURE);
}
std::array<unsigned char, 32> digest;
require(BCryptFinishHash(hash, digest.data(), digest.size(), 0) == 0,
"Finish snapshot SHA-256 failed", work.source->path, ERROR_GEN_FAILURE);
require(FlushFileBuffers(work.destination.get()), "Flush private snapshot failed", work.path);
work.digest = hex(digest.data(), digest.size());
} catch (const Failure& failure) {
work.failure = std::make_unique<Failure>(failure);
} catch (const std::exception& failure) {
work.failure = std::make_unique<Failure>(failure.what(), work.path, ERROR_GEN_FAILURE);
}
}
static void completeSnapshot(napi_env env, napi_status status, void* pointer) {
std::unique_ptr<SnapshotWork> work(static_cast<SnapshotWork*>(pointer));
work->root->snapshotPending = false;
try {
if (work->failure) throw *work->failure;
require(status == napi_ok && !work->root->snapshotCancelled.load(), "Native snapshot worker was cancelled", work->path, ERROR_OPERATION_ABORTED);
auto result = object(env);
set(env, result, "sha256", string(env, work->digest));
set(env, result, "source", identity(env, work->source->get(), work->source->requestedPath));
set(env, result, "snapshot", identity(env, work->destination.get(), work->path));
work->root->immutableFiles.push_back(std::move(work->destination));
check(napi_resolve_deferred(env, work->deferred, result));
} catch (const Failure& failure) {
napi_reject_deferred(env, work->deferred, failureValue(env, failure));
} catch (const std::exception& failure) {
napi_reject_deferred(env, work->deferred,
failureValue(env, Failure(failure.what(), work->path, ERROR_GEN_FAILURE)));
}
napi_delete_reference(env, work->rootReference);
napi_delete_async_work(env, work->work);
}
static napi_value snapshot(napi_env env, napi_value rootValue, Runtime& root,
const std::wstring& sourcePath, const std::wstring& relative) {
auto work = std::make_unique<SnapshotWork>(env, root);
work->source = openFile(sourcePath);
work->path = relativePath(root, relative);
work->destination = createPrivateFile(root, relative);
napi_value promise;
check(napi_create_promise(env, &work->deferred, &promise));
check(napi_create_reference(env, rootValue, 1, &work->rootReference));
const auto label = string(env, std::string("REA admitted Windows snapshot"));
root.snapshotCancelled.store(false);
try {
check(napi_create_async_work(env, nullptr, label, copySnapshot, completeSnapshot, work.get(), &work->work));
check(napi_queue_async_work(env, work->work));
} catch (...) {
if (work->work) napi_delete_async_work(env, work->work);
napi_delete_reference(env, work->rootReference);
throw;
}
root.snapshotPending = true;
work.release();
return promise;
}
napi_value filesystemCall(napi_env env, const std::wstring& operation, const std::vector<napi_value>& 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);
if (operation == L"open") {
auto file = openFile(wide(env, args[0]));
auto result = identity(env, file->get(), file->requestedPath);
set(env, result, "handle", wrap(env, std::move(file)));
return result;
}
if (operation == L"close") {
auto& file = static_cast<File&>(resource(env, args[0], Kind::File));
file.handles.clear(); file.closed = true;
return null(env);
}
if (operation == L"read") {
auto& file = static_cast<File&>(resource(env, args[0], Kind::File));
const auto position = numeric(env, args[1]);
const auto length = numeric(env, args[2]);
require(position >= 0 && position <= 9007199254740991.0 && position == static_cast<int64_t>(position) &&
length >= 0 && length <= 65536 && length == static_cast<DWORD>(length),
"Read coordinates exceed the native chunk boundary", file.path, ERROR_INVALID_PARAMETER);
LARGE_INTEGER offset; offset.QuadPart = static_cast<int64_t>(position);
require(SetFilePointerEx(file.get(), offset, nullptr, FILE_BEGIN), "Seek admitted file handle failed", file.path);
std::array<unsigned char, 65536> buffer;
DWORD count;
require(ReadFile(file.get(), buffer.data(), static_cast<DWORD>(length), &count, nullptr), "Read admitted file handle failed", file.path);
napi_value result;
check(napi_create_buffer_copy(env, count, buffer.data(), nullptr, &result));
return result;
}
if (operation == L"runtime_create") {
auto root = createRuntime(wide(env, args[0]), wide(env, args[1]));
auto result = identity(env, root->directory.get(), root->path);
set(env, result, "path", string(env, root->path));
set(env, result, "privateDacl", boolean(env, true));
set(env, result, "handle", wrap(env, std::move(root)));
return result;
}
auto& root = static_cast<Runtime&>(resource(env, args[0], Kind::Runtime));
if (operation == L"runtime_snapshot_cancel") { root.snapshotCancelled.store(true); return null(env); }
require(!root.snapshotPending, "Runtime snapshot is still pending", root.path, ERROR_BUSY);
// Reject overlapping operations before snapshot() resets cancellation. The
// one accepted worker and WindowsPrivateRuntime retain the same root lease.
if (operation == L"runtime_close") { closeRuntime(root); return null(env); }
if (operation == L"runtime_mkdir") { directory(root, wide(env, args[1])); return null(env); }
if (operation == L"runtime_open") {
const auto path = relativePath(root, wide(env, args[1]));
auto file = runtimeDirectory(root, path.substr(0, path.find_last_of(L'\\')));
file->path = path;
file->requestedPath = path;
file->handles.push_back(openComponent(path, GENERIC_READ, false));
verifyPrivate(file->get(), path, false);
auto result = identity(env, file->get(), path);
set(env, result, "handle", wrap(env, std::move(file)));
return result;
}
if (operation == L"runtime_write") {
bool isBuffer; check(napi_is_buffer(env, args[2], &isBuffer));
require(isBuffer, "Private write requires a byte buffer", root.path, ERROR_INVALID_PARAMETER);
void* bytes; size_t length; check(napi_get_buffer_info(env, args[2], &bytes, &length));
require(length <= MAXDWORD, "Private write exceeds Win32 byte representation", root.path, ERROR_INVALID_PARAMETER);
auto file = createPrivateFile(root, wide(env, args[1]));
writeBytes(file.get(), bytes, static_cast<DWORD>(length), root.path);
require(FlushFileBuffers(file.get()), "Flush private runtime file failed", root.path);
root.immutableFiles.push_back(std::move(file));
return null(env);
}
if (operation == L"runtime_snapshot") {
return snapshot(env, args[0], root, wide(env, args[1]), wide(env, args[2]));
}
throw Failure("Unknown native filesystem operation", L"", ERROR_INVALID_PARAMETER);
}
} // namespace rea
+271
View File
@@ -0,0 +1,271 @@
#include "authority.hpp"
namespace rea {
class Attributes {
std::vector<unsigned char> storage_;
public:
explicit Attributes(DWORD count) {
SIZE_T size = 0;
InitializeProcThreadAttributeList(nullptr, count, 0, &size);
storage_.resize(size);
require(InitializeProcThreadAttributeList(get(), count, 0, &size), "Initialize process attributes failed");
}
~Attributes() { DeleteProcThreadAttributeList(get()); }
LPPROC_THREAD_ATTRIBUTE_LIST get() { return reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage_.data()); }
void add(DWORD_PTR key, void* value, SIZE_T size) {
require(UpdateProcThreadAttribute(get(), 0, key, value, size, nullptr, nullptr),
"Windows atomic process attribute is unavailable");
}
};
static Handle createJob() {
Handle job(CreateJobObjectW(nullptr, nullptr));
require(job.valid(), "Create owned Job Object failed");
JOBOBJECT_EXTENDED_LIMIT_INFORMATION policy{};
policy.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
require(SetInformationJobObject(job.get(), JobObjectExtendedLimitInformation, &policy, sizeof(policy)),
"Apply kill-on-owner-close Job Object policy failed");
JOBOBJECT_EXTENDED_LIMIT_INFORMATION actual{};
require(QueryInformationJobObject(job.get(), JobObjectExtendedLimitInformation, &actual, sizeof(actual), nullptr),
"Read Job Object policy failed");
require(actual.BasicLimitInformation.LimitFlags == JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
"Job Object policy permits unexpected breakaway", L"", ERROR_ACCESS_DENIED);
return job;
}
static void pipe(Handle& read, Handle& write) {
SECURITY_ATTRIBUTES attributes{sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE};
HANDLE rawRead, rawWrite;
require(CreatePipe(&rawRead, &rawWrite, &attributes, 0), "Create owned process output pipe failed");
read.reset(rawRead); write.reset(rawWrite);
require(SetHandleInformation(read.get(), HANDLE_FLAG_INHERIT, 0), "Protect process output handle inheritance failed");
}
std::unique_ptr<Process> spawnProcess(const std::wstring& command, const std::wstring& commandLine,
const std::wstring& cwd, const std::vector<std::wstring>& environment) {
require(command.size() >= 3 && command[1] == L':' && command[2] == L'\\',
"Owned Windows process requires an absolute executable path", command, ERROR_INVALID_PARAMETER);
auto result = std::make_unique<Process>();
result->job = createJob();
Handle stdoutWrite, stderrWrite;
pipe(result->stdoutRead, stdoutWrite); pipe(result->stderrRead, stderrWrite);
SECURITY_ATTRIBUTES security{sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE};
Handle input(CreateFileW(L"NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
&security, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr));
require(input.valid(), "Open owned process null input failed");
Attributes attributes(2);
HANDLE job = result->job.get();
attributes.add(PROC_THREAD_ATTRIBUTE_JOB_LIST, &job, sizeof(job));
std::array<HANDLE, 3> inherited{input.get(), stdoutWrite.get(), stderrWrite.get()};
attributes.add(PROC_THREAD_ATTRIBUTE_HANDLE_LIST, inherited.data(), sizeof(inherited));
STARTUPINFOEXW startup{};
startup.StartupInfo.cb = sizeof(startup);
startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
startup.StartupInfo.hStdInput = input.get();
startup.StartupInfo.hStdOutput = stdoutWrite.get();
startup.StartupInfo.hStdError = stderrWrite.get();
startup.lpAttributeList = attributes.get();
// Windows environment names use ordinal case-insensitive comparison, not
// locale collation or JavaScript's expanding Unicode uppercase conversion.
auto orderedEnvironment = environment;
auto keyLength = [&](const std::wstring& entry) {
const auto end = entry.find(L'=', entry.front() == L'=' ? 1 : 0);
require(end != std::wstring::npos && end > 0, "Invalid child environment name", command,
ERROR_INVALID_PARAMETER);
return static_cast<int>(end);
};
for (const auto& entry : orderedEnvironment) {
require(!entry.empty(), "Empty child environment entry", command, ERROR_INVALID_PARAMETER);
keyLength(entry);
}
auto compareNames = [&](const std::wstring& left, const std::wstring& right) {
const auto result = CompareStringOrdinal(left.data(), keyLength(left), right.data(), keyLength(right), TRUE);
require(result != 0, "Compare Windows environment names failed", command);
return result;
};
std::stable_sort(orderedEnvironment.begin(), orderedEnvironment.end(),
[&](const std::wstring& left, const std::wstring& right) {
return compareNames(left, right) == CSTR_LESS_THAN;
});
std::vector<std::wstring> uniqueEnvironment;
for (auto& entry : orderedEnvironment) {
if (!uniqueEnvironment.empty() && compareNames(uniqueEnvironment.back(), entry) == CSTR_EQUAL)
uniqueEnvironment.back() = std::move(entry);
else uniqueEnvironment.push_back(std::move(entry));
}
std::vector<wchar_t> variables;
for (const auto& entry : uniqueEnvironment) {
variables.insert(variables.end(), entry.begin(), entry.end()); variables.push_back(L'\0');
}
variables.push_back(L'\0');
if (uniqueEnvironment.empty()) variables.push_back(L'\0');
std::vector<wchar_t> line(commandLine.begin(), commandLine.end()); line.push_back(L'\0');
PROCESS_INFORMATION process{};
require(CreateProcessW(command.c_str(), line.data(), nullptr, nullptr, TRUE,
CREATE_UNICODE_ENVIRONMENT | EXTENDED_STARTUPINFO_PRESENT | CREATE_SUSPENDED | CREATE_NO_WINDOW,
variables.data(), cwd.empty() ? nullptr : cwd.c_str(), &startup.StartupInfo, &process),
"Create process atomically inside owned Job Object failed", command);
result->process.reset(process.hProcess);
Handle thread(process.hThread);
result->pid = process.dwProcessId;
// An elevated token may default file ownership to Administrators. Normalize
// only the suspended child's default owner so its runtime files belong to the
// current user; the caller's token and privileges are not modified.
HANDLE rawToken;
require(OpenProcessToken(result->process.get(), TOKEN_QUERY | TOKEN_ADJUST_DEFAULT, &rawToken),
"Open suspended process default-owner token failed", command);
Handle token(rawToken);
DWORD tokenSize = 0;
GetTokenInformation(token.get(), TokenUser, nullptr, 0, &tokenSize);
std::vector<unsigned char> tokenUser(tokenSize);
require(GetTokenInformation(token.get(), TokenUser, tokenUser.data(), tokenSize, &tokenSize),
"Read suspended process user identity failed", command);
TOKEN_OWNER owner{reinterpret_cast<TOKEN_USER*>(tokenUser.data())->User.Sid};
require(SetTokenInformation(token.get(), TokenOwner, &owner, sizeof(owner)),
"Set suspended process file owner failed", command);
DWORD_PTR affinity = 0, systemAffinity = 0;
require(GetProcessAffinityMask(GetCurrentProcess(), &affinity, &systemAffinity),
"Read caller process affinity failed", command);
if (affinity != 0)
require(SetProcessAffinityMask(result->process.get(), affinity), "Preserve caller process affinity failed", command);
const DWORD priority = GetPriorityClass(GetCurrentProcess());
require(priority != 0 && SetPriorityClass(result->process.get(), priority),
"Preserve caller process priority failed", command);
BOOL assigned = FALSE;
if (!IsProcessInJob(result->process.get(), result->job.get(), &assigned) || !assigned) {
TerminateJobObject(result->job.get(), 1);
throw Failure("Suspended process has no owned Job Object membership", command, ERROR_ACCESS_DENIED);
}
require(ResumeThread(thread.get()) != MAXDWORD, "Resume job-owned process failed", command);
return result;
}
static napi_value readOutput(napi_env env, Handle& read, bool& ended) {
std::array<unsigned char, 65536> bytes;
DWORD available = 0, count = 0;
if (!read.valid()) ended = true;
else if (!PeekNamedPipe(read.get(), nullptr, 0, nullptr, &available, nullptr)) {
require(GetLastError() == ERROR_BROKEN_PIPE, "Observe owned process output failed");
read.reset(); ended = true;
} else if (available > 0) {
require(ReadFile(read.get(), bytes.data(), std::min<DWORD>(available, bytes.size()), &count, nullptr),
"Read owned process output failed");
}
napi_value result;
check(napi_create_buffer_copy(env, count, bytes.data(), nullptr, &result));
return result;
}
static DWORD activeProcesses(Process& process) {
JOBOBJECT_BASIC_ACCOUNTING_INFORMATION state{};
require(QueryInformationJobObject(process.job.get(), JobObjectBasicAccountingInformation, &state, sizeof(state), nullptr),
"Observe owned Job Object settlement failed");
return state.ActiveProcesses;
}
static napi_value callerToken(napi_env env) {
HANDLE raw;
require(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_DUPLICATE, &raw), "Read caller token failed");
Handle token(raw);
DWORD size;
TOKEN_ELEVATION elevation{};
require(GetTokenInformation(token.get(), TokenElevation, &elevation, sizeof(elevation), &size), "Read caller elevation failed");
std::vector<unsigned char> user(4096), owner(4096), integrity(4096);
require(GetTokenInformation(token.get(), TokenUser, user.data(), user.size(), &size) &&
GetTokenInformation(token.get(), TokenOwner, owner.data(), owner.size(), &size) &&
GetTokenInformation(token.get(), TokenIntegrityLevel, integrity.data(), integrity.size(), &size),
"Read caller token observations failed");
HANDLE rawImpersonation;
require(DuplicateToken(token.get(), SecurityIdentification, &rawImpersonation), "Observe caller group membership failed");
Handle impersonation(rawImpersonation);
std::array<unsigned char, SECURITY_MAX_SID_SIZE> administrators;
DWORD administratorSize = administrators.size();
require(CreateWellKnownSid(WinBuiltinAdministratorsSid, nullptr, administrators.data(), &administratorSize),
"Create administrator group identity failed");
BOOL administrator = FALSE, assigned = FALSE;
require(CheckTokenMembership(impersonation.get(), administrators.data(), &administrator), "Read caller administrator membership failed");
require(IsProcessInJob(GetCurrentProcess(), nullptr, &assigned), "Read caller job membership failed");
const auto sid = reinterpret_cast<TOKEN_MANDATORY_LABEL*>(integrity.data())->Label.Sid;
auto result = object(env);
set(env, result, "elevated", boolean(env, elevation.TokenIsElevated != 0));
set(env, result, "administrator", boolean(env, administrator != FALSE));
set(env, result, "integrityLevel", number(env, *GetSidSubAuthority(sid, *GetSidSubAuthorityCount(sid) - 1)));
set(env, result, "defaultOwnerIsUser", boolean(env, EqualSid(reinterpret_cast<TOKEN_USER*>(user.data())->User.Sid,
reinterpret_cast<TOKEN_OWNER*>(owner.data())->Owner)));
set(env, result, "inJob", boolean(env, assigned != FALSE));
return result;
}
napi_value processCall(napi_env env, const std::wstring& operation, const std::vector<napi_value>& args) {
if (operation == L"process_caller_token") {
require(args.empty(), "Caller token observation takes no arguments", L"", ERROR_INVALID_PARAMETER);
return callerToken(env);
}
if (operation == L"process_spawn") {
require(args.size() == 4, "Wrong native process launch argument count", L"", ERROR_INVALID_PARAMETER);
std::vector<std::wstring> environment;
for (const auto& entry : array(env, args[3])) environment.push_back(wide(env, entry));
auto process = spawnProcess(wide(env, args[0]), wide(env, args[1]), wide(env, args[2]), environment);
auto result = object(env);
set(env, result, "pid", number(env, process->pid));
set(env, result, "jobAssigned", boolean(env, true));
set(env, result, "killOnOwnerClose", boolean(env, true));
set(env, result, "handle", wrap(env, std::move(process)));
return result;
}
require(args.size() == 1, "Wrong native process handle argument count", L"", ERROR_INVALID_PARAMETER);
auto& process = static_cast<Process&>(resource(env, args[0], Kind::Process));
if (operation == L"process_poll") {
auto result = object(env);
bool stdoutEnded = false, stderrEnded = false;
set(env, result, "stdout", readOutput(env, process.stdoutRead, stdoutEnded));
set(env, result, "stderr", readOutput(env, process.stderrRead, stderrEnded));
set(env, result, "stdoutEnded", boolean(env, stdoutEnded));
set(env, result, "stderrEnded", boolean(env, stderrEnded));
const auto exited = WaitForSingleObject(process.process.get(), 0);
require(exited == WAIT_OBJECT_0 || exited == WAIT_TIMEOUT, "Observe owned process exit failed");
DWORD code = 0;
if (exited == WAIT_OBJECT_0) require(GetExitCodeProcess(process.process.get(), &code), "Read owned process exit code failed");
set(env, result, "exitCode", exited == WAIT_OBJECT_0 ? number(env, code) : null(env));
set(env, result, "activeProcesses", number(env, activeProcesses(process)));
return result;
}
if (operation == L"process_alive") return number(env, activeProcesses(process));
if (operation == L"process_terminate") {
const auto active = activeProcesses(process);
if (active > 0) require(TerminateJobObject(process.job.get(), 1), "Terminate owned Job Object failed");
return boolean(env, active > 0);
}
if (operation == L"process_close") {
// Closing the job is the crash-safe authority; no PID enumeration is used.
process.job.reset(); process.process.reset(); process.stdoutRead.reset(); process.stderrRead.reset();
process.closed = true;
return null(env);
}
throw Failure("Unknown native process operation", L"", ERROR_INVALID_PARAMETER);
}
napi_value inspect(napi_env env) {
wchar_t temp[32768];
const auto length = GetTempPathW(32768, temp);
require(length > 0 && length < 32768, "Read temporary directory coordinate failed");
auto root = createRuntime(std::wstring(temp, length), L"rea-native-probe-");
auto filesystem = identity(env, root->directory.get(), root->path);
closeRuntime(*root);
auto job = createJob();
Attributes attributes(1);
HANDLE raw = job.get();
attributes.add(PROC_THREAD_ATTRIBUTE_JOB_LIST, &raw, sizeof(raw));
auto result = object(env);
set(env, result, "abiVersion", number(env, 1));
set(env, result, "nodeApiVersion", number(env, 8));
set(env, result, "architecture", string(env, std::string("x64")));
set(env, result, "filesystem", filesystem);
set(env, result, "privateDacl", boolean(env, true));
set(env, result, "atomicJobAssignment", boolean(env, true));
set(env, result, "killOnOwnerClose", boolean(env, true));
return result;
}
} // namespace rea
+1197 -1202
View File
File diff suppressed because it is too large Load Diff
+28 -23
View File
@@ -35,7 +35,7 @@
"rea-agents": "scripts/rea.mjs"
},
"engines": {
"node": "^22.19.0 || >=24.11.0"
"node": "^22.19.0 || ^24.11.0 || >=26.0.0"
},
"packageManager": "npm@11.16.0",
"files": [
@@ -44,6 +44,7 @@
"bridge/hopper_bridge.py",
"bridge/native/ReaNativeUI.swift",
"bridge/ghidra/ReaGhidraBridge.java",
"bridge/ghidra/ReaGhidraPrepareCom.java",
"scripts/rea.mjs",
"scripts/electron-active-hook.cjs",
"scripts/electron-active-hook-boundaries.cjs",
@@ -52,7 +53,10 @@
"scripts/prepare.mjs",
"skills",
"README.md",
"LICENSE"
"LICENSE",
"native/windows/build/manifest.json",
"native/windows/build/rea-windows-x64.node",
"scripts/verify-windows-native-artifact.mjs"
],
"scripts": {
"deps:check": "node scripts/check-dependency-install.mjs",
@@ -73,7 +77,7 @@
"precheck:test": "npm run deps:check",
"check:test": "turbo run typecheck lint format:check knip metadata:check test:run",
"precheck:pr": "npm run deps:check",
"check:pr": "turbo run typecheck lint format:check knip metadata:check test:run && npm run docs:check",
"check:pr": "turbo run typecheck lint format:check knip metadata:check test:run && npm run docs:check && npm run jscpd && npm run scan:todos",
"precheck:ci": "npm run deps:check",
"check:ci": "turbo run typecheck lint format:check knip metadata:check jscpd scan:todos",
"build:cached": "turbo run build",
@@ -82,7 +86,6 @@
"lint": "oxlint",
"lint:fix": "oxlint --fix",
"knip": "knip",
"lint:dead": "knip",
"jscpd": "jscpd src/ tests/",
"scan:todos": "node scripts/scan-todos.mjs",
"start": "node scripts/rea.mjs mcp",
@@ -121,6 +124,7 @@
"verify:ghidra": "npm run build:cached && node scripts/verify-real-ghidra.mjs",
"verify:ghidra:switch": "npm run build:cached && node scripts/verify-real-ghidra-switch.mjs",
"verify:ghidra:dos": "npm run build:cached && node scripts/verify-real-ghidra-dos.mjs",
"verify:ghidra:com": "npm run build:cached && node scripts/verify-real-ghidra-com.mjs",
"verify:ghidra:aarch64-jump-table": "npm run build:cached && node scripts/verify-real-ghidra.mjs --aarch64-jump-table",
"verify:interface-builder": "npm run build:cached && node scripts/verify-interface-builder.mjs",
"verify:ghidra:cross-format": "npm run build:cached && node scripts/verify-real-ghidra.mjs --cross-format",
@@ -129,6 +133,7 @@
"verify:electron": "npm run build:cached && node scripts/verify-real-electron.mjs",
"verify:inspector": "npm run build:cached && node scripts/verify-real-javascript-runtime-observation.mjs",
"verify:javascript-runtime": "npm run build:cached && node scripts/verify-local-javascript-runtime.mjs",
"verify:javascript:digests": "npm run build:cached && node scripts/verify-large-javascript-digests.mjs",
"verify:application-workflows": "npm run build:cached && node scripts/verify-local-application-workflows.mjs",
"verify:managed": "npm run build:cached && node scripts/verify-managed-conformance.mjs",
"verify:agent": "npm run build:cached && node scripts/verify-agent-experience.mjs",
@@ -145,8 +150,6 @@
"config:print": "node scripts/print-mcp-config.mjs",
"evidence:generate": "npm run build:cached && node scripts/generate-completion-ledger.mjs",
"evidence:check": "npm run build:cached && node scripts/generate-completion-ledger.mjs --check",
"docs:api": "typedoc",
"docs:api:cached": "turbo run docs:api",
"docs:generate": "node scripts/run-exclusive.mjs docs npm run docs:generate:unlocked",
"docs:generate:unlocked": "npm run metadata:generate && npm run build:cached && node scripts/generate-mcp-tool-catalog.mjs && node scripts/generate-skill-metadata.mjs && node scripts/generate-product-catalog.mjs && node scripts/generate-completion-ledger.mjs && node scripts/generate-error-schema.mjs",
"docs:check": "node scripts/run-exclusive.mjs docs turbo run docs:check:built",
@@ -156,7 +159,12 @@
"prepare": "node scripts/prepare.mjs",
"verify:asset-catalog": "npm run build:cached && node scripts/verify-asset-catalog.mjs",
"verify:native-ui:permissions": "npm run build:cached && node scripts/verify-native-ui.mjs --allow-permission-denial",
"test:focused": "node scripts/run-development-tests.mjs focused"
"test:focused": "node scripts/run-development-tests.mjs focused",
"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:windows-native": "node scripts/verify-windows-native.mjs",
"verify:ghidra:windows:package": "node scripts/verify-packaged-ghidra-windows.mjs"
},
"lint-staged": {
"*.{cjs,cts,js,jsx,mjs,mts,ts,tsx}": [
@@ -172,48 +180,45 @@
"@electron/asar": "4.2.0",
"@jridgewell/trace-mapping": "0.3.31",
"@lydell/node-pty": "1.1.0",
"@modelcontextprotocol/client": "2.0.0",
"@modelcontextprotocol/server": "2.0.0",
"@modelcontextprotocol/client": "2.3.1",
"@modelcontextprotocol/server": "2.3.1",
"@xterm/addon-serialize": "0.14.0",
"@xterm/headless": "6.0.0",
"@zip.js/zip.js": "2.8.26",
"canonicalize": "3.0.0",
"cross-spawn": "7.0.6",
"diff": "9.0.0",
"graphology": "0.26.0",
"graphology-shortest-path": "2.1.0",
"ignore": "7.0.6",
"incur": "0.4.13",
"incur": "0.6.1",
"isomorphic-git": "1.38.7",
"jsonc-parser": "3.3.1",
"pino": "9.14.0",
"pino": "10.4.0",
"playwright-core": "1.58.2",
"plist": "5.0.0",
"semver": "7.8.5",
"smol-toml": "^1.7.0",
"smol-toml": "1.7.0",
"write-file-atomic": "7.0.0",
"ws": "8.21.0",
"zod": "4.4.3"
},
"devDependencies": {
"@fast-check/vitest": "0.4.1",
"@fast-check/vitest": "0.5.0",
"@types/cross-spawn": "6.0.6",
"@types/node": "24.10.1",
"@types/node": "26.6.4",
"@types/semver": "7.7.1",
"@types/write-file-atomic": "4.0.3",
"@types/ws": "8.18.1",
"@vitest/coverage-v8": "4.1.10",
"@vitest/coverage-v8": "5.0.3",
"ajv": "8.20.0",
"husky": "9.1.7",
"jscpd": "5.0.12",
"knip": "6.26.0",
"knip": "6.39.0",
"lint-staged": "16.4.0",
"oxfmt": "0.72.0",
"oxlint": "1.73.0",
"turbo": "2.10.5",
"typedoc": "0.28.20",
"typescript": "5.9.3",
"vitest": "4.1.10",
"oxlint": "1.87.0",
"turbo": "2.11.7",
"typescript": "7.0.2",
"vitest": "5.0.3",
"yaml": "2.9.0"
}
}
+1
View File
@@ -21,6 +21,7 @@
{ "type": "generic", "path": "README_ja.md" },
{ "type": "generic", "path": "README_ko.md" },
{ "type": "generic", "path": "README_ar.md" },
{ "type": "generic", "path": "docs/installation.md" },
{
"type": "generic",
"path": "src/generatedPackageMetadata.ts"
+150
View File
@@ -0,0 +1,150 @@
#!/usr/bin/env node
import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
const nodeVersion = "22.19.0";
const compiler = "x86_64-w64-mingw32-g++";
const cache = join(homedir(), ".cache", "rea-windows-native");
const output = join(root, "native", "windows", "build");
const run = (command, args) => {
const result = spawnSync(command, args, {
cwd: root,
encoding: "utf8",
maxBuffer: 4 * 1_024 * 1_024,
timeout: 120_000,
});
if (result.error !== undefined)
throw new Error(
`Windows native build lane requires ${command}: ${result.error.message}`,
);
if (result.status !== 0)
throw new Error(
`Windows native build failed: ${result.stdout}${result.stderr}`,
);
return result.stdout;
};
if (process.platform !== "linux")
throw new Error(
"The Windows x64 artifact build lane currently requires Linux and MinGW-w64.",
);
run(compiler, ["--version"]);
await mkdir(cache, { recursive: true });
await mkdir(output, { recursive: true });
const exists = async (path) =>
access(path).then(
() => true,
() => false,
);
const fetchBytes = async (name) => {
const response = await fetch(
`https://nodejs.org/dist/v${nodeVersion}/${name}`,
{
signal: AbortSignal.timeout(60_000),
},
);
if (!response.ok)
throw new Error(
`Node build prerequisite download failed: ${name}: HTTP ${response.status}`,
);
return Buffer.from(await response.arrayBuffer());
};
const checksums = (await fetchBytes("SHASUMS256.txt")).toString("utf8");
const verifiedDownload = async (name, path) => {
if (!(await exists(path))) await writeFile(path, await fetchBytes(name));
const digest = createHash("sha256")
.update(await readFile(path))
.digest("hex");
const expected = checksums
.split("\n")
.find((line) => line.slice(66) === name)
?.slice(0, 64);
if (expected === undefined || digest !== expected)
throw new Error(`Node build prerequisite SHA-256 mismatch: ${name}`);
};
const cachedHeaders = join(
homedir(),
".cache",
"node-gyp",
nodeVersion,
"include",
"node",
);
let headers = cachedHeaders;
if (!(await exists(join(headers, "node_api.h")))) {
const archive = join(cache, `node-v${nodeVersion}-headers.tar.gz`);
await verifiedDownload(`node-v${nodeVersion}-headers.tar.gz`, archive);
run("tar", ["xzf", archive, "-C", cache]);
headers = join(cache, `node-v${nodeVersion}`, "include", "node");
}
const artifact = "rea-windows-x64.node";
// MSVC short-import libraries do not produce a correct Node import table with
// GNU ld. Generate a GNU import library for the exact stable Node-API symbols.
const sources = ["addon.cc", "filesystem.cc", "process.cc"];
const sourceText = (
await Promise.all(
sources.map((path) =>
readFile(join(root, "native", "windows", "src", path), "utf8"),
),
)
).join("\n");
const symbols = [
...new Set(
[...sourceText.matchAll(/\b(napi_[a-z0-9_]+)\s*\(/gu)].map(
(match) => match[1],
),
),
].sort();
const definition = join(cache, "node-api.def");
const library = join(cache, "libnode-api.a");
await writeFile(
definition,
`LIBRARY node.exe\nEXPORTS\n${symbols.join("\n")}\n`,
);
run("x86_64-w64-mingw32-dlltool", ["-d", definition, "-l", library]);
run(compiler, [
"-std=c++17",
"-O2",
"-DNAPI_VERSION=8",
"-D_WIN32_WINNT=0x0A00",
"-shared",
"-static",
"-static-libgcc",
"-static-libstdc++",
"-Wl,--no-insert-timestamp",
`-I${headers}`,
"native/windows/src/addon.cc",
"native/windows/src/filesystem.cc",
"native/windows/src/process.cc",
library,
"-ladvapi32",
"-lbcrypt",
"-lntdll",
"-o",
join(output, artifact),
]);
const packageJson = JSON.parse(
await readFile(join(root, "package.json"), "utf8"),
);
const bytes = await readFile(join(output, artifact));
const metadata = {
packageVersion: packageJson.version,
platform: "win32",
architecture: "x64",
abiVersion: 1,
nodeApiVersion: 8,
artifact,
artifactSha256: createHash("sha256").update(bytes).digest("hex"),
};
await writeFile(
join(output, "manifest.json"),
`${JSON.stringify(metadata, null, 2)}\n`,
);
process.stdout.write(
`${JSON.stringify({ ...metadata, artifactBytes: bytes.length })}\n`,
);
+2
View File
@@ -109,6 +109,8 @@ const canonicalizeJson = (value) => {
const payloadJson = JSON.stringify(
canonicalizeJson({ catalog, auxiliaryProviders }),
null,
2,
);
const source = await formatGeneratedFile(
"src/generatedMcpToolCatalog.ts",
+3 -3
View File
@@ -6,12 +6,12 @@ export const toolFamilyCatalog = (sources) => {
{
id: "direct",
surface: "official-proxy",
contracts: sources.toolContracts.OFFICIAL_TOOL_CONTRACTS,
contracts: sources.officialContracts.OFFICIAL_TOOL_CONTRACTS,
},
{
id: "enhanced",
surface: "enhanced",
contracts: sources.toolContracts.ENHANCED_TOOL_CONTRACTS,
contracts: sources.enhancedContracts.ENHANCED_TOOL_CONTRACTS,
},
{
id: "native",
@@ -59,7 +59,7 @@ export const toolFamilyCatalog = (sources) => {
{
id: "session",
surface: "session",
contracts: sources.toolContracts.SESSION_TOOL_CONTRACTS,
contracts: sources.sessionContracts.SESSION_TOOL_CONTRACTS,
},
].map(({ id, surface, contracts }) => ({
id,
+3
View File
@@ -37,6 +37,9 @@ const SOURCE_PATHS = {
catalogIdentity: "dist/catalogIdentity.js",
cli: "dist/cli.js",
toolContracts: "dist/contracts/toolContracts.js",
officialContracts: "dist/contracts/officialToolContracts.js",
enhancedContracts: "dist/contracts/enhancedToolContracts.js",
sessionContracts: "dist/contracts/sessionToolContracts.js",
nativeContracts: "dist/contracts/nativeToolContracts.js",
artifactContracts: "dist/contracts/artifactToolContracts.js",
managedContracts: "dist/contracts/managedToolContracts.js",
+1 -1
View File
@@ -39,7 +39,7 @@ const observeVerifierLineage = async (run, observedAt) => {
run,
observedAt,
null,
"Windows verifier lineage ownership is unavailable without Job Objects",
"The verifier has no retained native Job Object lease for lineage observation; provider jobs are verified by their native owners",
);
try {
const { members, observerPid } = await processSnapshot();
+1 -1
View File
@@ -23,7 +23,7 @@ const runtimeFiles = isMcpMode
if (!(await compiledRuntimeExists(runtimeFiles))) {
process.stderr.write(
`REA's compiled runtime is missing. Run \`npm ci\` in ${packageRoot} to install dependencies and build REA, then restart it. If this is an installed package, reinstall rea-agents.\n`,
`REA's compiled runtime is missing. Run \`npm ci && npm run build:cached\` in ${packageRoot} to install dependencies and build REA, then restart it. If this is an installed package, reinstall rea-agents.\n`,
);
process.exitCode = 1;
} else if (isMcpMode) {
@@ -0,0 +1,38 @@
#!/usr/bin/env node
import assert from "node:assert/strict";
import { constants } from "node:buffer";
import { createHash } from "node:crypto";
import { canonicalDigest } from "../dist/domain/comparisonSemantics.js";
import { createEvidence, parseEvidence } from "../dist/domain/evidence.js";
// This opt-in check crosses the actual engine string limit; keep it outside
// routine source tests. Build first, then run this script with the local Node.
const leaf = "x".repeat(1024 * 1024);
const encodedLeaf = JSON.stringify(leaf);
const count = Math.ceil(constants.MAX_STRING_LENGTH / encodedLeaf.length) + 1;
const value = { payload: Array.from({ length: count }, () => leaf) };
const expected = createHash("sha256");
expected.update('{"payload":[');
for (let index = 0; index < count; index += 1) {
if (index > 0) expected.update(",");
expected.update(encodedLeaf);
}
expected.update("]}");
assert.equal(canonicalDigest(value), expected.digest("hex"));
const evidence = createEvidence(
undefined,
{ id: "large-json-fixture", name: "Large JSON fixture", version: "1" },
{ operation: "inspect_fixture", parameters: {}, result: value },
);
assert.equal(parseEvidence(evidence).evidence_id, evidence.evidence_id);
process.stdout.write(
`${JSON.stringify({
verified: true,
serialized_value_bytes: count * encodedLeaf.length + count - 1 + 14,
engine_string_limit: constants.MAX_STRING_LENGTH,
evidence_id: evidence.evidence_id,
})}\n`,
);
+6 -1
View File
@@ -12,10 +12,15 @@ const buildManagedFixtures = async (workspace) => {
writeFile(
managedPath,
buildManagedPeFixture({
methods: [
{ name: "Main", flags: 0x0016 },
{ name: "NativeMessageBox", flags: 0x2016, rva: 0 },
],
pinvoke: {
moduleName: "user32.dll",
importName: "MessageBoxW",
mappingFlags: 0x0345,
memberRow: 2,
},
}),
),
@@ -59,7 +64,7 @@ const verifyManagedMembers = async ({ cli, managedPath, environment }) => {
);
if (
managedMembers.operation !== "inspect_managed_members" ||
managedMembers.normalized_result?.methods?.length !== 1
managedMembers.normalized_result?.methods?.length !== 2
)
throw new Error("packaged managed member CLI failed");
return managedMembers;
+303
View File
@@ -0,0 +1,303 @@
#!/usr/bin/env node
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import {
mkdtemp,
mkdir,
readFile,
readdir,
rm,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { promisify } from "node:util";
import { pathToFileURL } from "node:url";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
if (process.platform !== "win32" || process.arch !== "x64")
throw new Error(
"Packaged Windows Ghidra acceptance requires a Windows x64 host.",
);
const workspace = await mkdtemp(join(tmpdir(), "rea-packaged-ghidra-"));
const exec = promisify(execFile);
let packageRoot = resolve(process.argv[2] ?? ".");
// The default lane verifies the npm artifact in an isolated prefix. Explicit
// package roots support an already-installed artifact without a second install.
if (process.argv[2] === undefined) {
try {
const npmEntry =
process.env.npm_execpath ??
join(dirname(process.execPath), "node_modules/npm/bin/npm-cli.js");
const packed = JSON.parse(
(
await exec(
process.execPath,
[
npmEntry,
"pack",
"--json",
"--ignore-scripts",
"--pack-destination",
workspace,
],
{ timeout: 120_000, maxBuffer: 8 * 1024 * 1024 },
)
).stdout,
);
assert.equal(
packed.length,
1,
"The package lane must produce one artifact.",
);
const prefix = join(workspace, "installed");
await exec(
process.execPath,
[
npmEntry,
"install",
"--prefix",
prefix,
"--ignore-scripts",
"--omit=dev",
"--no-audit",
"--no-fund",
join(workspace, packed[0].filename),
],
{ timeout: 120_000, maxBuffer: 8 * 1024 * 1024 },
);
packageRoot = join(prefix, "node_modules", "rea-agents");
} catch (cause) {
await rm(workspace, { recursive: true, force: true });
throw cause;
}
}
const target = resolve(
process.argv[3] ?? "build/fixtures/rea-ghidra-windows.exe",
);
let TOOL_CONTRACTS, native, token, sha256;
try {
({ TOOL_CONTRACTS } = await import(
pathToFileURL(join(packageRoot, "dist/contracts/toolContracts.js"))
));
const { requireWindowsNativeAuthority } = await import(
pathToFileURL(join(packageRoot, "dist/windows/WindowsNativeLoader.js"))
);
native = requireWindowsNativeAuthority();
token = native.call("process_caller_token", []);
assert.equal(
token.administrator,
false,
"The real-provider lane must run as an ordinary user.",
);
assert.equal(
token.elevated,
false,
"The real-provider lane must use a non-elevated token.",
);
const digest = (bytes) => createHash("sha256").update(bytes).digest("hex");
sha256 = digest(await readFile(target));
} catch (cause) {
await rm(workspace, { recursive: true, force: true });
throw cause;
}
const digest = (bytes) => createHash("sha256").update(bytes).digest("hex");
const runtimeParent = join(workspace, "runtime with spaces");
await mkdir(runtimeParent);
const environment = {
...process.env,
REA_ANALYSIS_PROVIDER: "ghidra",
REA_LOG_LEVEL: "error",
GHIDRA_HEADLESS_MAXMEM: "512m",
NODE_OPTIONS: "--max-old-space-size=512",
TEMP: runtimeParent,
TMP: runtimeParent,
HOME: workspace,
USERPROFILE: workspace,
APPDATA: join(workspace, "appdata"),
LOCALAPPDATA: join(workspace, "localappdata"),
};
const entry = join(packageRoot, "scripts/rea.mjs");
const report = {
ok: false,
platform: "win32",
architecture: "x64",
nonAdmin: true,
targetSha256: sha256,
cli: {},
mcpOperations: [],
nativeControls: "available",
runtimeCleanup: false,
};
const assertCleanup = async () => {
const entries = await readdir(runtimeParent);
report.runtimeResidualCount = entries.length;
report.runtimeResidualKinds = entries.map((name) =>
name.startsWith("rea-")
? "rea-runtime"
: name.startsWith("hsperfdata_")
? "jvm-performance-data"
: "other",
);
assert.equal(entries.length, 0, "Provider runtime cleanup left files.");
};
try {
const providers = JSON.parse(
(
await exec(process.execPath, [entry, "providers", "--json"], {
env: environment,
timeout: 30_000,
})
).stdout,
);
assert.ok(JSON.stringify(providers).includes("ghidra"));
report.cli.providers = true;
const inspected = await exec(
process.execPath,
[entry, "inspect", target, "--provider", "ghidra", "--format", "json"],
{ env: environment, timeout: 360_000, maxBuffer: 8 * 1024 * 1024 },
);
const inspection = JSON.parse(inspected.stdout);
assert.ok(inspection.error === undefined);
report.cli.inspect = true;
await assertCleanup();
const transport = new StdioClientTransport({
command: process.execPath,
args: [entry, "mcp"],
env: environment,
stderr: "pipe",
});
const client = new Client({
name: "rea-packaged-windows-ghidra",
version: "1.0.0",
});
const call = async (name, arguments_) => {
report.lastOperation = name;
if (process.argv[4] !== undefined)
await writeFile(process.argv[4], `${JSON.stringify(report)}\n`);
const contract = TOOL_CONTRACTS.find((value) => value.name === name);
assert.ok(contract !== undefined, `Missing canonical contract: ${name}`);
const argumentsParsed = contract.inputSchema.parse(arguments_);
const result = await client.callTool(
{ name, arguments: argumentsParsed },
{ timeout: 360_000 },
);
assert.notEqual(result.isError, true, `Packaged operation failed: ${name}`);
const structured =
result.structuredContent ??
JSON.parse(result.content.find((item) => item.type === "text").text);
const parsed = contract.outputSchema.parse(structured);
report.mcpOperations.push(name);
return parsed.result;
};
try {
await client.connect(transport);
await call("open_binary", { path: target, provider_id: "ghidra" });
assert.equal((await call("list_documents", {})).length, 1);
await call("list_names", {});
const procedures = await call("list_procedures", {});
assert.ok(procedures.length > 0);
assert.ok((await call("list_segments", {})).length > 0);
await call("list_strings", {});
const procedure =
procedures.find((item) => item.procedure?.external === false) ??
procedures[0];
assert.ok(procedure !== undefined);
const loadImage = await call("inspect_native_load_image", {});
assert.equal(
loadImage.status,
"unsupported",
"PE load-image attestation must remain explicitly unsupported.",
);
assert.ok(loadImage.observations !== undefined);
const memory = await call("read_bytes", {
address: procedure.address,
length: 16,
});
const mapping = await call("address_to_file_offset", {
address: procedure.address,
});
assert.equal(memory.complete, true);
assert.equal(memory.returned_bytes, 16);
assert.equal(
memory.bytes_hex,
(await readFile(target))
.subarray(mapping.file_offset, mapping.file_offset + 16)
.toString("hex"),
);
await call("address_name", { address: procedure.address });
assert.equal(
await call("procedure_address", { procedure: procedure.value }),
procedure.address,
);
await call("resolve_containing_procedure", { address: procedure.address });
await call("search_procedures", { pattern: procedure.value });
await call("search_strings", { pattern: "rea" });
for (const name of [
"procedure_assembly",
"procedure_callees",
"procedure_callers",
"procedure_info",
"procedure_pseudo_code",
"read_function_instructions",
"procedure_references",
"analyze_function",
])
await call(name, { procedure: procedure.value });
await call("xrefs", { address: procedure.address });
await call("inspect_native_data_type", { type: "/undefined8" });
await call("inspect_native_instruction", { address: procedure.address });
await call("resolve_native_call_targets", { address: procedure.address });
const expected = (
await import(
pathToFileURL(join(packageRoot, "dist/ghidra/GhidraSessionValues.js"))
)
).GHIDRA_SESSION_CAPABILITIES.filter(
(name) =>
name !== "ping" &&
name !== "shutdown" &&
name !== "annotate_native_function",
);
assert.ok(
expected.every((name) => report.mcpOperations.includes(name)),
"Packaged verification omitted an admitted operation.",
);
await call("binary_session", {});
await call("close_binary", {});
await assertCleanup();
} finally {
await client.close();
}
assert.equal(
digest(await readFile(target)),
sha256,
"Analysis modified the selected target.",
);
assert.deepEqual(
native.call("process_caller_token", []),
token,
"Analysis changed caller token authority.",
);
report.runtimeCleanup = true;
report.ok = true;
if (process.argv[4] !== undefined)
await writeFile(process.argv[4], `${JSON.stringify(report)}\n`);
process.stdout.write(`${JSON.stringify(report)}\n`);
} catch (cause) {
report.failure = {
name: cause.name,
message: cause.message
.replaceAll(packageRoot, "<package>")
.replaceAll(target, "<target>")
.replaceAll(workspace, "<workspace>"),
};
if (process.argv[4] !== undefined)
await writeFile(process.argv[4], `${JSON.stringify(report)}\n`);
throw cause;
} finally {
await rm(workspace, { recursive: true, force: true });
}
+5 -1
View File
@@ -27,7 +27,11 @@ export async function verifyPackedBridge({
"extends HeadlessScript",
'request.method.equals("ping")',
'request.method.equals("shutdown")',
'result.addProperty("read_only", true)',
'boolean readOnly = !descriptor.transport.equals("unix-socket")',
'result.addProperty("read_only", readOnly)',
'case "annotate_native_function"',
'currentProgram.startTransaction("REA function annotations")',
"currentProgram.endTransaction(transaction, commit)",
"analysisTimeoutOccurred()",
])
if (!ghidraSource.includes(commitment))
+1 -1
View File
@@ -36,7 +36,7 @@ import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs";
import { verifyLargeScreenshotE2e } from "./lib/browser-screenshot-e2e.mjs";
import { verifyPopupEventCoverage } from "./lib/browser-popup-e2e.mjs";
const REAL_BROWSER_STARTUP_TIMEOUT_MS = 30_000;
const REAL_BROWSER_STARTUP_TIMEOUT_MS = 60_000;
const SCENARIO_SECRET_VALUE = "rea-browser-verifier-secret";
const SCENARIO_URL_SECRET_VALUE = "rea-browser-url-verifier-secret";
process.env.REA_BROWSER_VERIFIER_SECRET = SCENARIO_SECRET_VALUE;
+366
View File
@@ -0,0 +1,366 @@
#!/usr/bin/env node
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { isAbsolute, join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { parseEvidence } from "../dist/domain/evidence.js";
import { functionDossierSchema } from "../dist/domain/hopperValues.js";
import { inspectGhidraInstallation } from "../dist/ghidra/GhidraInstallation.js";
import { buildDosComFixture } from "../tests/conformance/ghidra/dos-com-fixture.mjs";
import { createVerifierRun, completeVerifierRun } from "./lib/verifier-run.mjs";
// This lane intentionally has no game paths, binary seeds or compiler dependency.
if (process.argv.length !== 2)
throw new Error("Usage: node scripts/verify-real-ghidra-com.mjs");
if (!["linux", "darwin"].includes(process.platform))
throw new Error(
"verify:ghidra:com supports Linux/macOS hosts only; Windows P0 is PE x86-64 only.",
);
if (process.env.GHIDRA_INSTALL_DIR === undefined)
throw new Error(
"verify:ghidra:com prerequisite missing: GHIDRA_INSTALL_DIR (bring your own Ghidra).",
);
const installation = inspectGhidraInstallation({
installDir: process.env.GHIDRA_INSTALL_DIR,
...(process.env.JAVA_HOME === undefined
? {}
: { javaHome: process.env.JAVA_HOME }),
});
if (installation.status !== "available")
throw new Error(
`verify:ghidra:com prerequisite unavailable: ${JSON.stringify(installation)}`,
);
const captureDirectory = process.env.REA_COM_PROOF_CAPTURE_DIR;
if (captureDirectory !== undefined) {
assert.ok(
isAbsolute(captureDirectory),
"REA_COM_PROOF_CAPTURE_DIR must be absolute",
);
await mkdir(captureDirectory, { recursive: true, mode: 0o700 });
}
const packageRoot = process.env.REA_COM_PROOF_PACKAGE_ROOT;
if (packageRoot !== undefined && !isAbsolute(packageRoot))
throw new Error("REA_COM_PROOF_PACKAGE_ROOT must be absolute");
const entrypoint =
packageRoot === undefined
? fileURLToPath(new URL("./rea.mjs", import.meta.url))
: join(packageRoot, "scripts", "rea.mjs");
const run = createVerifierRun();
const workspace = await mkdtemp(join(tmpdir(), "rea-com-proof-"));
const runtime = join(workspace, "runtime");
await mkdir(runtime);
const fixture = buildDosComFixture();
const targetPath = join(workspace, "fixture.com");
await writeFile(targetPath, fixture.bytes, { mode: 0o600 });
const sha256 = digest(fixture.bytes);
const env = {
PATH: process.env.PATH ?? "/usr/bin:/bin",
TMPDIR: runtime,
REA_LOG_LEVEL: "silent",
REA_ANALYSIS_PROVIDER: "ghidra",
REA_PROCESS_RUN_ID: run.run_id,
HOPPER_LAUNCHER_PATH: "/rea-unconfigured-deep-provider/hopper",
GHIDRA_INSTALL_DIR: process.env.GHIDRA_INSTALL_DIR,
...(process.env.JAVA_HOME === undefined
? {}
: { JAVA_HOME: process.env.JAVA_HOME }),
};
const transport = new StdioClientTransport({
command: process.execPath,
args: [entrypoint, "mcp"],
env,
stderr: "pipe",
});
const client = new Client({ name: "rea-real-com-proof", version: "1" });
let opened = false;
let stderr = "";
let report;
transport.stderr?.on("data", (chunk) => {
stderr = (stderr + chunk.toString()).slice(-65536);
});
try {
await client.connect(transport);
const untyped = await client.callTool({
name: "open_binary",
arguments: { path: targetPath, provider_id: "ghidra" },
});
assert.equal(
untyped.isError,
true,
"Headerless bytes were guessed as COM without explicit interpretation",
);
const target = await call("open_binary", {
path: targetPath,
provider_id: "ghidra",
format: "dos-com",
});
opened = true;
assert.equal(target.format, "dos-com");
assert.equal(target.architecture, "x86");
assert.equal(target.sha256, sha256);
const image = await call("inspect_native_load_image");
assert.equal(
image.status,
"verified",
JSON.stringify(image.checks?.filter((c) => !c.matched)),
);
assert.equal(image.format, "dos-com");
assert.equal(image.header_bytes, 0);
assert.equal(image.module_bytes, fixture.bytes.length);
assert.equal(image.entry.linear_address, fixture.entry);
assert.equal(image.entry.offset, 256);
assert.equal(image.observations.entry_context[0].registers.length, 4);
const memory = await call("read_bytes", {
address: fixture.entry,
length: fixture.bytes.length,
});
assert.equal(memory.bytes_hex, fixture.bytes.toString("hex"));
assert.equal(memory.complete, true);
const mapping = await call("address_to_file_offset", {
address: fixture.near,
});
assert.equal(mapping.file_offset, 32);
const psp = await call("read_bytes", { address: "0x10000", length: 16 });
assert.equal(psp.returned_bytes, 0);
assert.equal(psp.complete, false);
const tail = await call("read_bytes", { address: "0x1013e", length: 8 });
assert.equal(tail.returned_bytes, 2);
assert.equal(tail.complete, false);
const procedures = await call("list_procedures");
assert.ok(procedures.some((p) => p.address === fixture.entry));
assert.ok(procedures.some((p) => p.address === fixture.near));
const dossier = functionDossierSchema.parse(
await call("analyze_function", { procedure: fixture.entry }),
);
assert.ok(dossier.pseudocode.trim().length > 0);
assert.equal(dossier.procedure.body.available, true);
const instruction = await call("inspect_native_instruction", {
address: fixture.entry,
});
assert.equal(
instruction.bytes.replaceAll(" ", "").toLowerCase(),
fixture.entry_hex,
);
const cliImage = await cli("inspect-native-load-image");
const stable = (x) => ({
...x,
observations: {
...x.observations,
source_files: x.observations.source_files.map(
({ name, ...file }) => file,
),
},
});
assert.deepEqual(stable(cliImage.normalized_result), stable(image));
assert.deepEqual(
(
await cli("read-bytes", fixture.entry, [
"--length",
String(fixture.bytes.length),
])
).normalized_result,
memory,
);
assert.deepEqual(
(await cli("address-to-file-offset", fixture.near)).normalized_result,
mapping,
);
const changes = {
procedure: fixture.entry,
name: "rea_entry",
comment: "Regular\nUnicode 註記",
inline_comment: "Inline finding",
};
// Prime provider inventories and the session snapshot before edits.
await call("list_names");
const updated = await call("annotate_native_function", changes);
assert.equal(updated.annotations.name, changes.name);
assert.equal(updated.annotations.comment, changes.comment);
assert.equal(updated.annotations.inline_comment, changes.inline_comment);
assert.equal(updated.dossier.procedure.name, changes.name);
assert.ok(updated.dossier.pseudocode.includes(changes.name));
assert.equal(
await call("procedure_address", { procedure: changes.name }),
fixture.entry,
);
assert.equal(
await call("address_name", { address: fixture.entry }),
changes.name,
);
assert.ok(
(await call("list_procedures")).some((p) => p.value === changes.name),
);
assert.ok((await call("list_names")).some((p) => p.value === changes.name));
assert.equal(
(await call("analyze_function", { procedure: fixture.entry })).procedure
.name,
changes.name,
);
const rejected = await client.callTool({
name: "annotate_native_function",
arguments: {
procedure: fixture.entry,
comment: "MUST ROLL BACK",
name: "invalid name\n",
},
});
assert.equal(
rejected.isError,
true,
"Ghidra accepted an invalid function name",
);
const retained = await call("annotate_native_function", {
procedure: fixture.entry,
name: changes.name,
});
assert.equal(
retained.annotations.comment,
changes.comment,
"Failed edit leaked its earlier comment write",
);
assert.equal(retained.annotations.inline_comment, changes.inline_comment);
assert.equal(retained.dossier.procedure.name, changes.name);
const cleared = await call("annotate_native_function", {
procedure: fixture.entry,
comment: "",
inline_comment: "",
});
assert.equal(cleared.annotations.comment, null);
assert.equal(cleared.annotations.inline_comment, null);
assert.ok(!cleared.dossier.comments.some((c) => c.address === fixture.entry));
assert.equal(
(
await call("read_bytes", {
address: fixture.entry,
length: fixture.bytes.length,
})
).bytes_hex,
fixture.bytes.toString("hex"),
);
assert.equal((await call("inspect_native_load_image")).status, "verified");
const cliAnnotated = await cli("annotate-native-function", fixture.entry, [
"--name",
changes.name,
"--comment",
changes.comment,
"--inline-comment",
changes.inline_comment,
]);
assert.deepEqual(cliAnnotated.normalized_result, updated);
if (captureDirectory !== undefined)
await writeFile(
join(captureDirectory, "image.json"),
JSON.stringify(image, null, 2),
{ mode: 0o600 },
);
await call("close_binary");
opened = false;
assert.equal(digest(await readFile(targetPath)), sha256);
report = {
ok: true,
mocked: false,
lane: "ghidra-com",
packaged_artifact: packageRoot !== undefined,
host: process.platform,
provider: { id: "ghidra", version: installation.providerVersion },
target: { format: "dos-com", sha256, bytes: fixture.bytes.length },
load_image: {
status: image.status,
checks: image.checks.length,
entry: fixture.entry,
entry_context: image.observations.entry_context,
},
transport: { cli: true, stdio_mcp: true },
memory_evidence: {
complete_file_read: true,
source_offset: 32,
psp_unmapped: true,
partial_read_bytes: 2,
},
functions: { entry: true, near: true, pseudocode_nonempty: true },
annotations: {
atomic_rollback: true,
fresh_inventories: true,
fresh_decompiler: true,
clear_comments: true,
cli_mcp_parity: true,
},
original_unchanged: true,
limitations: image.limitations,
};
} catch (error) {
if (stderr.trim()) process.stderr.write(stderr);
throw error;
} finally {
if (opened)
await call("close_binary").catch((error) =>
process.stderr.write(String(error)),
);
await client.close();
await transport.close();
await rm(workspace, { recursive: true, force: true });
}
assert.ok(report);
const verifierRun = await completeVerifierRun(run);
assert.equal(verifierRun.process_lineage.status, "verified");
assert.deepEqual(verifierRun.process_lineage.descendants, []);
process.stdout.write(
JSON.stringify({
verifier_run: verifierRun,
...report,
cleanup: "complete",
}) + "\n",
);
function digest(bytes) {
return createHash("sha256").update(bytes).digest("hex");
}
async function call(name, args = {}) {
const value = await client.callTool(
{ name, arguments: args },
{ timeout: 240000 },
);
assert.notEqual(value.isError, true, JSON.stringify(value));
if (name === "open_binary") return value.structuredContent.result;
if (name === "close_binary") return value.structuredContent;
const evidence = parseEvidence(value.structuredContent.evidence);
assert.equal(evidence.subject.digest.sha256, sha256);
assert.deepEqual(evidence.normalized_result, value.structuredContent.result);
return value.structuredContent.result;
}
async function cli(command, address, options = []) {
const { stdout } = await promisify(execFile)(
process.execPath,
[
entrypoint,
command,
targetPath,
...(address === undefined ? [] : [address]),
...options,
"--target-format",
"dos-com",
"--provider",
"ghidra",
"--json",
],
{ env, timeout: 240000, maxBuffer: 16 * 1024 * 1024 },
);
const evidence = parseEvidence(JSON.parse(stdout));
assert.equal(evidence.subject.digest.sha256, sha256);
assert.equal(evidence.subject.format, "dos-com");
assert.equal(evidence.analysis_profile.parameters.loader, "BinaryLoader");
assert.equal(
evidence.analysis_profile.parameters.language_id,
"x86:LE:16:Real Mode",
);
assert.equal(evidence.analysis_profile.parameters.entry_offset, "0x100");
assert.equal(digest(await readFile(targetPath)), sha256);
return evidence;
}
+100 -3
View File
@@ -106,6 +106,78 @@ try {
assert.equal(target.kind, "executable");
assert.equal(target.architecture, "x86");
assert.equal(target.sha256, sha256);
const image = await call("inspect_native_load_image");
assert.equal(
image.status,
"verified",
JSON.stringify(image.checks?.filter((check) => !check.matched)),
);
assert.equal(image.target_sha256, sha256);
assert.equal(image.header_bytes, fixture.header_bytes);
assert.equal(image.module_bytes, fixture.module_bytes);
assert.equal(image.entry.linear_address, expected.entry);
assert.ok(image.checks.every((check) => check.matched));
const cliImage = await cliEvidence("inspect-native-load-image");
// Snapshot filenames are session-specific. Every measured byte/range/check is stable.
const stableImage = (value) => ({
...value,
observations: {
...value.observations,
source_files: value.observations.source_files.map(
({ name: _name, ...file }) => file,
),
},
});
assert.deepEqual(stableImage(cliImage.normalized_result), stableImage(image));
const mapped = await call("address_to_file_offset", {
address: expected.entry,
});
assert.equal(mapped.file_offset, fixture.header_bytes);
const headerMapping = await call("address_to_file_offset", {
address: "HEADER:0x0",
});
assert.equal(headerMapping.file_offset, 0);
const fileRelocation = await call("address_to_file_offset", {
address: address(fixture.relocation_offset),
});
assert.equal(
fileRelocation.file_offset,
fixture.header_bytes + fixture.relocation_offset,
);
const memoryRelocation = await call("read_bytes", {
address: address(fixture.relocation_offset),
length: 2,
});
assert.equal(memoryRelocation.bytes_hex, "0410");
assert.equal(memoryRelocation.complete, true);
assert.deepEqual(
(
await cliEvidence("read-bytes", address(fixture.relocation_offset), [
"--length",
"2",
])
).normalized_result,
memoryRelocation,
);
assert.deepEqual(
(await cliEvidence("address-to-file-offset", expected.entry))
.normalized_result,
mapped,
);
const tail = await call("read_bytes", {
address: address(fixture.module_bytes - 2),
length: 8,
});
assert.equal(tail.returned_bytes, 2);
assert.equal(tail.complete, false);
const unmapped = await call("read_bytes", { address: "0x80000", length: 8 });
assert.equal(unmapped.returned_bytes, 0);
assert.equal(unmapped.complete, false);
const noSource = await client.callTool({
name: "address_to_file_offset",
arguments: { address: "0x80000" },
});
assert.equal(noSource.isError, true);
const procedures = await call("list_procedures");
assert.ok(
Array.isArray(procedures),
@@ -330,6 +402,22 @@ try {
load_segment: profile.parameters.load_segment,
},
transport: { cli: true, stdio_mcp: true },
load_image: {
status: image.status,
checks: image.checks.length,
mappings: image.observations.mappings.length,
relocations: image.observations.relocations.length,
cli_mcp_parity: true,
},
memory_evidence: {
relocated_word_hex: memoryRelocation.bytes_hex,
entry_file_offset: mapped.file_offset,
header_file_offset: headerMapping.file_offset,
partial_read_bytes: tail.returned_bytes,
unmapped_read_bytes: unmapped.returned_bytes,
unmapped_file_offset_rejected: true,
cli_mcp_parity: true,
},
functions: facts,
instruction_oracles: {
entry_bytes: hexBytes(move.bytes),
@@ -400,13 +488,21 @@ function hexBytes(bytes) {
return bytes.replace(/\s/gu, "").toLowerCase();
}
function assertProfile(profile) {
assert.equal(
profile.parameters.load_image_evidence,
"independent-mz-mapping-relocations-v1",
);
assert.equal(
profile.parameters.function_body_evidence,
"complete-inclusive-ranges-v1",
);
assert.equal(profile.provider.id, "ghidra");
assert.equal(profile.parameters.target_format, "dos-mz");
assert.equal(profile.parameters.import_mode, "ephemeral-read-only");
assert.equal(profile.parameters.import_mode, "ephemeral-source-immutable");
assert.equal(
profile.parameters.annotation_policy,
"atomic-function-entry-metadata-v1",
);
assert.equal(profile.parameters.loader, "MzLoader");
assert.equal(profile.parameters.language_id, "x86:LE:16:Real Mode");
assert.equal(profile.parameters.compiler_spec_id, "default");
@@ -471,14 +567,15 @@ async function evidenceCall(name, arguments_) {
assertProfile(evidence.analysis_profile.parameters.upstream_analysis_profile);
return evidence;
}
async function cliEvidence(command, procedure) {
async function cliEvidence(command, procedure, options = []) {
const { stdout } = await promisify(execFile)(
process.execPath,
[
entrypoint,
command,
targetPath,
procedure,
...(procedure === undefined ? [] : [procedure]),
...options,
"--provider",
"ghidra",
"--json",
+63 -20
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env node
import { access } from "node:fs/promises";
import { access, readFile } from "node:fs/promises";
import { isAbsolute, resolve } from "node:path";
import { fileURLToPath } from "node:url";
@@ -22,16 +22,26 @@ import {
} from "../dist/ghidra/GhidraInstallation.js";
import { GhidraHeadlessLauncher } from "../dist/ghidra/GhidraLauncher.js";
import { GHIDRA_PROVIDER_IDENTITY } from "../dist/ghidra/GhidraProvider.js";
import { GHIDRA_SESSION_CAPABILITIES as SESSION_CAPABILITIES } from "../dist/ghidra/GhidraSessionValues.js";
import { windowsP0Capabilities } from "../dist/ghidra/GhidraProviderCapabilities.js";
import { GHIDRA_SESSION_CAPABILITIES } from "../dist/ghidra/GhidraSessionValues.js";
import { parseBinaryTarget } from "../dist/application/BinaryTargetResolver.js";
import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs";
const verifierRun = createVerifierRun();
const SESSION_CAPABILITIES = GHIDRA_SESSION_CAPABILITIES.filter(
(name) => name !== "annotate_native_function",
);
if (process.platform !== "win32" || process.arch !== "x64")
throw new Error(
"The real Windows Ghidra verifier requires a Windows x64 host",
);
if (
windowsP0Capabilities().some(
({ available, effects }) => available && effects.mutatesArtifact,
)
)
throw new Error("Windows Ghidra must not advertise database mutation");
const installDir = process.env.GHIDRA_INSTALL_DIR;
if (installDir === undefined || !isAbsolute(installDir))
throw new Error(
@@ -74,6 +84,7 @@ if (!profile.ok || profile.value.profile === null)
throw new Error("Windows Ghidra profile could not be committed");
const client = new GhidraClient({
platform: installation.platform,
launcher: new GhidraHeadlessLauncher({
analyzeHeadlessPath: installation.analyzeHeadlessPath,
...(process.env.JAVA_HOME === undefined
@@ -113,19 +124,41 @@ try {
if (
!Array.isArray(documents) ||
documents.length !== 1 ||
!pageHasItems(procedures) ||
!Array.isArray(procedures) ||
procedures.length === 0 ||
!Array.isArray(segments) ||
segments.length === 0 ||
!isPage(names) ||
!isPage(strings)
!Array.isArray(names) ||
!Array.isArray(strings)
)
throw new Error("Windows Ghidra inventory proof was incomplete");
const procedure = procedures.items.find(
const procedure = procedures.find(
(item) => item.procedure?.external === false,
);
if (procedure === undefined)
throw new Error("Windows Ghidra fixture exposed no local procedure");
await inventory("inspect_native_load_image", {});
const memory = await inventory("read_bytes", {
address: procedure.address,
length: 16,
});
const mapping = await inventory("address_to_file_offset", {
address: procedure.address,
});
const sourceBytes = await readFile(targetPath);
if (
memory.complete !== true ||
memory.returned_bytes !== 16 ||
memory.bytes_hex !==
sourceBytes
.subarray(mapping.file_offset, mapping.file_offset + 16)
.toString("hex")
)
throw new Error(
"Windows loaded bytes disagree with the observed source-file mapping",
);
await inventory("address_name", { address: procedure.address });
const resolvedAddress = await inventory("procedure_address", {
procedure: procedure.value,
@@ -149,13 +182,22 @@ try {
])
await functionOperation(operation, { procedure: procedure.value });
await functionOperation("xrefs", { address: procedure.address });
await functionOperation("inspect_native_data_type", { type: "/undefined8" });
await functionOperation("inspect_native_instruction", {
address: procedure.address,
});
await functionOperation("resolve_native_call_targets", {
address: procedure.address,
});
await functionOperation("analyze_function", {
procedure: procedure.value,
});
const expected = [
...GHIDRA_INVENTORY_OPERATIONS,
...GHIDRA_FUNCTION_OPERATIONS,
...GHIDRA_FUNCTION_OPERATIONS.filter(
(name) => name !== "annotate_native_function",
),
];
if (
observed.size !== expected.length ||
@@ -178,11 +220,16 @@ try {
transport: "authenticated-loopback-tcp",
operations: [...observed].sort((left, right) => left.localeCompare(right)),
cleanup: "complete",
native_controls: {
job_object: true,
protected_dacl: true,
handle_admission: true,
},
limitations: [
"approved-non-sensitive-fixtures-only",
"no-job-object-ownership",
"no-private-dacl-proof",
"no-reparse-point-authority",
"windows-x64-local-ntfs-only",
"native-x86-64-pe-applications-only",
"no-gui-or-mutation-authority",
],
};
} finally {
@@ -226,7 +273,9 @@ function assertSession(session, targetSha256, profileDigest) {
session.read_only !== true ||
session.analysis_complete !== true ||
session.analysis_timed_out !== false ||
session.capabilities.join(",") !== SESSION_CAPABILITIES.join(",")
session.capabilities.length !== SESSION_CAPABILITIES.length ||
new Set(session.capabilities).size !== SESSION_CAPABILITIES.length ||
SESSION_CAPABILITIES.some((name) => !session.capabilities.includes(name))
)
throw new Error(
`Windows Ghidra session commitment drifted: ${JSON.stringify(session)}`,
@@ -240,7 +289,9 @@ function assertRuntimeCoordinates(runtime, targetSha256) {
typeof runtime.runtime_root !== "string" ||
typeof runtime.endpoint_path !== "string" ||
typeof runtime.project_root !== "string" ||
typeof runtime.process_id !== "number"
typeof runtime.process_id !== "number" ||
typeof runtime.target_admission !== "object" ||
runtime.target_admission === null
)
throw new Error(
`Windows Ghidra runtime coordinates are incomplete: ${JSON.stringify(runtime)}`,
@@ -262,14 +313,6 @@ async function assertCleanup(runtime) {
);
}
const isPage = (value) =>
typeof value === "object" &&
value !== null &&
!Array.isArray(value) &&
Array.isArray(value.items);
const pageHasItems = (value) => isPage(value) && value.items.length > 0;
async function exists(path) {
try {
await access(path);
@@ -0,0 +1,39 @@
#!/usr/bin/env node
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
const root = new URL("../", import.meta.url);
const packageJson = JSON.parse(
await readFile(new URL("package.json", root), "utf8"),
);
const manifest = JSON.parse(
await readFile(new URL("native/windows/build/manifest.json", root), "utf8"),
);
const bytes = await readFile(
new URL("native/windows/build/rea-windows-x64.node", root),
);
if (
manifest.packageVersion !== packageJson.version ||
manifest.platform !== "win32" ||
manifest.architecture !== "x64" ||
manifest.abiVersion !== 1 ||
manifest.nodeApiVersion !== 8 ||
manifest.artifact !== "rea-windows-x64.node" ||
createHash("sha256").update(bytes).digest("hex") !== manifest.artifactSha256
)
throw new Error(
"Windows native artifact metadata or SHA-256 does not match this package; run the Windows native build lane.",
);
const offset = bytes.length >= 64 ? bytes.readUInt32LE(0x3c) : bytes.length;
if (
bytes.toString("ascii", 0, 2) !== "MZ" ||
offset > bytes.length - 26 ||
bytes.toString("ascii", offset, offset + 4) !== "PE\0\0" ||
bytes.readUInt16LE(offset + 4) !== 0x8664 ||
bytes.readUInt16LE(offset + 24) !== 0x20b
)
throw new Error("Windows native artifact must be a Windows x64 PE32+ image.");
process.stdout.write(
`${JSON.stringify({ ok: true, ...manifest, artifactBytes: bytes.length })}\n`,
);
+427
View File
@@ -0,0 +1,427 @@
#!/usr/bin/env node
import assert from "node:assert/strict";
import { execFileSync, spawn } from "node:child_process";
import { createHash } from "node:crypto";
import {
access,
mkdir,
mkdtemp,
readFile,
rename,
rm,
symlink,
writeFile,
open,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
if (process.platform !== "win32")
throw new Error(
"Windows native conformance requires a real Windows x64 host.",
);
const packageRoot = resolve(process.argv[2] ?? ".");
const { requireWindowsNativeAuthority } = await import(
pathToFileURL(join(packageRoot, "dist/windows/WindowsNativeLoader.js"))
);
const native = requireWindowsNativeAuthority();
const { WindowsPrivateRuntime } = await import(
pathToFileURL(join(packageRoot, "dist/windows/WindowsPrivateRuntime.js"))
);
const workspace = await mkdtemp(join(tmpdir(), "rea-native-conformance-"));
const environment = Object.entries(process.env)
.filter(([, value]) => value !== undefined)
.map(([key, value]) => `${key}=${value}`);
const quote = (value) =>
`"${value.replace(/(\\*)"/gu, '$1$1\\"').replace(/(\\+)$/u, "$1$1")}"`;
const delay = () => new Promise((resolve) => setTimeout(resolve, 25));
const exists = (path) =>
access(path).then(
() => true,
() => false,
);
const live = (pid) => {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
};
const launch = (arguments_) =>
native.call("process_spawn", [
process.execPath,
[process.execPath, ...arguments_].map(quote).join(" "),
workspace,
environment,
]);
const wait = async (child) => {
let output = "";
for (let attempt = 0; attempt < 400; attempt++) {
const state = native.call("process_poll", [child.handle]);
output += state.stdout.toString();
if (
state.exitCode !== null &&
state.activeProcesses === 0 &&
state.stdoutEnded &&
state.stderrEnded
)
return { ...state, output };
await delay();
}
throw new Error("Owned job did not settle within the fixture deadline.");
};
const report = { ok: false, artifact: "verified", controls: {}, processes: {} };
try {
const sourceDirectory = join(workspace, "source");
await mkdir(sourceDirectory);
const source = join(sourceDirectory, "target.bin");
await writeFile(source, Buffer.alloc(1024 * 1024, 0x37));
const snapshotOwner = WindowsPrivateRuntime.create(
workspace,
"single-flight-",
);
try {
const rejectedController = new AbortController();
const accepted = snapshotOwner.snapshot(source, "accepted.bin");
const rejected = snapshotOwner.snapshot(
source,
"rejected.bin",
rejectedController.signal,
);
rejectedController.abort();
await assert.rejects(rejected, /Runtime snapshot is still pending/u);
const completed = await accepted;
assert.equal(
completed.sha256,
createHash("sha256")
.update(await readFile(source))
.digest("hex"),
);
assert.equal(
await exists(join(snapshotOwner.observation.path, "rejected.bin")),
false,
);
report.controls.singleFlightCancellationOwnership = true;
} finally {
await snapshotOwner.close();
}
const unrelatedFile = join(workspace, "unrelated-file");
await writeFile(unrelatedFile, "preserve unrelated writes");
const admitted = native.call("open", [source]);
try {
await assert.rejects(
rename(sourceDirectory, `${sourceDirectory}-replacement`),
);
await assert.rejects(open(source, "r+"));
await rename(unrelatedFile, `${unrelatedFile}-renamed`);
if (process.argv[3] !== undefined) {
const observation = JSON.parse(
execFileSync(
resolve(process.argv[3]),
["reparse-directory", sourceDirectory, workspace],
{ encoding: "utf8" },
),
);
assert.equal(
observation.reparseConversionDenied,
true,
"An admitted ancestor was converted into a junction.",
);
report.controls.inPlaceAncestorReparseDenied = true;
}
assert.throws(() => native.call("read", [{}, 0, 1]));
assert.throws(() => native.call("read", [admitted.handle, NaN, 1]));
assert.equal(native.call("read", [admitted.handle, 0, 1])[0], 0x37);
} finally {
native.call("close", [admitted.handle]);
}
assert.throws(() => native.call("read", [admitted.handle, 0, 1]));
const junction = join(workspace, "junction");
await symlink(sourceDirectory, junction, "junction");
assert.throws(
() => native.call("open", [join(junction, "target.bin")]),
/Reparse/u,
);
assert.throws(() => native.call("open", [source + ":stream"]));
const runtime = native.call("runtime_create", [
workspace,
"private root with spaces-",
]);
const sentinel = join(sourceDirectory, "sentinel");
await writeFile(sentinel, "preserve");
try {
const acl = JSON.parse(
execFileSync(
"powershell.exe",
[
"-NoProfile",
"-NonInteractive",
"-Command",
"$a=Get-Acl -LiteralPath $env:REA_TEST_PRIVATE_RUNTIME_PATH; $u=[Security.Principal.WindowsIdentity]::GetCurrent().User; @{protected=$a.AreAccessRulesProtected; ownerMatchesUser=($a.GetOwner([Security.Principal.SecurityIdentifier]).Value -eq $u.Value); trusteesOnlyUserAndSystem=(@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]) | Where-Object {$_.IdentityReference.Value -ne $u.Value -and $_.IdentityReference.Value -ne 'S-1-5-18'}).Count -eq 0); count=@($a.Access).Count} | ConvertTo-Json -Compress",
],
{
encoding: "utf8",
// A pwsh caller can supply module paths incompatible with the
// Windows PowerShell observer. Let that observer build its own path.
env: {
...Object.fromEntries(
Object.entries(process.env).filter(
([name]) => name.toLowerCase() !== "psmodulepath",
),
),
REA_TEST_PRIVATE_RUNTIME_PATH: runtime.path,
},
},
),
);
assert.deepEqual(acl, {
protected: true,
ownerMatchesUser: true,
trusteesOnlyUserAndSystem: true,
count: 2,
});
native.call("runtime_mkdir", [runtime.handle, "inputs"]);
native.call("runtime_write", [
runtime.handle,
"descriptor.json",
Buffer.from("fixture"),
]);
assert.throws(() =>
native.call("runtime_write", [
runtime.handle,
"descriptor.json",
Buffer.from("replace"),
]),
);
assert.throws(() =>
native.call("runtime_mkdir", [runtime.handle, "..\\escape"]),
);
const pending = native.call("runtime_snapshot", [
runtime.handle,
source,
"inputs\\target.bin",
]);
assert.ok(pending instanceof Promise);
assert.throws(
() => native.call("runtime_close", [runtime.handle]),
/pending/u,
);
const snapshot = await pending;
assert.equal(
snapshot.sha256,
createHash("sha256")
.update(await readFile(source))
.digest("hex"),
);
assert.equal(snapshot.source.requestedPath, source);
await assert.rejects(
writeFile(join(runtime.path, "inputs", "target.bin"), "replace"),
);
await symlink(
sourceDirectory,
join(runtime.path, "outside-junction"),
"junction",
);
const cancelled = native.call("runtime_snapshot", [
runtime.handle,
source,
"cancelled.bin",
]);
native.call("runtime_snapshot_cancel", [runtime.handle]);
await assert.rejects(cancelled, /cancelled/u);
report.controls = {
...report.controls,
protectedDaclReadback: true,
sourceReplacementDenied: true,
sourceWriteDenied: true,
unrelatedFilesystemRenamePreserved: true,
junctionAdmissionDenied: true,
alternateStreamsDenied: true,
forgedAndClosedHandlesDenied: true,
immutableSnapshotDigest: true,
asynchronousSnapshot: true,
snapshotCancellation: true,
};
} finally {
native.call("runtime_close", [runtime.handle]);
}
assert.equal(await exists(runtime.path), false);
assert.equal(await readFile(sentinel, "utf8"), "preserve");
report.controls.cleanupDoesNotTraverseJunctions = true;
const fixture = join(workspace, "tree.mjs");
await writeFile(
fixture,
`import {spawn} from 'node:child_process'; import {writeFileSync} from 'node:fs';
const depth=Number(process.argv[2]); writeFileSync(process.argv[3]+depth,String(process.pid));
if(depth>0)spawn(process.execPath,[import.meta.filename,String(depth-1),process.argv[3]],{detached:true,stdio:'ignore'});
setInterval(()=>{},1000);\n`,
);
const pidPrefix = join(workspace, "pid-");
const child = launch(["--max-old-space-size=128", fixture, "2", pidPrefix]);
const unrelated = spawn(
process.execPath,
["--max-old-space-size=128", "-e", "setInterval(()=>{},1000)"],
{ stdio: "ignore" },
);
try {
for (
let attempt = 0;
attempt < 200 && !(await exists(pidPrefix + "0"));
attempt++
)
await delay();
const pids = await Promise.all(
[0, 1, 2].map(async (depth) =>
Number(await readFile(pidPrefix + depth, "utf8")),
),
);
assert.ok(native.call("process_poll", [child.handle]).activeProcesses >= 3);
native.call("process_terminate", [child.handle]);
assert.equal((await wait(child)).activeProcesses, 0);
assert.equal(pids.some(live), false);
assert.ok(unrelated.pid !== undefined && live(unrelated.pid));
report.processes.descendantsAndDetachedDescendantsTerminated = true;
report.processes.unrelatedProcessPreserved = true;
} finally {
native.call("process_terminate", [child.handle]);
await wait(child);
native.call("process_close", [child.handle]);
if (unrelated.exitCode === null) {
const closed = new Promise((resolve) => unrelated.once("close", resolve));
unrelated.kill();
await closed;
}
}
const ownerClose = launch([
"--max-old-space-size=128",
fixture,
"0",
join(workspace, "owner-close-"),
]);
native.call("process_close", [ownerClose.handle]);
for (let attempt = 0; attempt < 100 && live(ownerClose.pid); attempt++)
await delay();
assert.equal(live(ownerClose.pid), false);
report.processes.killOnOwnerClose = true;
const exited = launch([
"--max-old-space-size=128",
"-e",
"console.log('observed');process.exit(7)",
]);
const settled = await wait(exited);
assert.equal(settled.exitCode, 7);
assert.match(settled.output, /observed/u);
native.call("process_close", [exited.handle]);
report.processes.normalExitAndOutput = true;
const boundaryFixture = process.argv[3];
if (boundaryFixture !== undefined) {
const before = JSON.parse(
execFileSync(boundaryFixture, [], { encoding: "utf8" }),
);
const boundary = native.call("process_spawn", [
boundaryFixture,
`${quote(boundaryFixture)} breakaway`,
workspace,
environment,
]);
const denied = await wait(boundary);
native.call("process_close", [boundary.handle]);
assert.equal(JSON.parse(denied.output).breakawayDenied, true);
const tokenChild = native.call("process_spawn", [
boundaryFixture,
quote(boundaryFixture),
workspace,
environment,
]);
const observed = await wait(tokenChild);
native.call("process_close", [tokenChild.handle]);
assert.equal(JSON.parse(observed.output).defaultOwnerIsUser, true);
const after = JSON.parse(
execFileSync(boundaryFixture, [], { encoding: "utf8" }),
);
assert.deepEqual(after, before);
report.processes.breakawayDenied = true;
report.processes.childOwnerNormalizedWithoutChangingCaller = true;
report.callerToken = before;
const environmentChild = native.call("process_spawn", [
boundaryFixture,
`${quote(boundaryFixture)} environment`,
workspace,
[
"z_REA=z",
"_REA=underscore",
"A_REA=a",
"REA_CASE=first",
"rea_case=last",
"REA_ß=sharp",
"REA_SS=double",
],
]);
const childEnvironment = await wait(environmentChild);
native.call("process_close", [environmentChild.handle]);
assert.deepEqual(JSON.parse(childEnvironment.output), {
ordinallySorted: true,
lastDuplicateSelected: true,
unicodeNamesPreserved: true,
});
report.processes.windowsEnvironmentSemantics = true;
}
const ownerFixture = join(workspace, "owner.mjs");
const ownerPidFile = join(workspace, "crash-child.pid");
const moduleUrl = pathToFileURL(
join(packageRoot, "dist/windows/WindowsNativeLoader.js"),
).href;
await writeFile(
ownerFixture,
`import {writeFileSync} from 'node:fs';
import {requireWindowsNativeAuthority} from ${JSON.stringify(moduleUrl)};
const native=requireWindowsNativeAuthority();
const env=Object.entries(process.env).map(([k,v])=>k+'='+v);
const child=native.call('process_spawn',[process.execPath,${JSON.stringify([process.execPath, "--max-old-space-size=128", fixture, "0", join(workspace, "crash-descendant-")].map(quote).join(" "))},${JSON.stringify(workspace)},env]);
writeFileSync(${JSON.stringify(ownerPidFile)},String(child.pid));setInterval(()=>{},1000);\n`,
);
const owner = spawn(
process.execPath,
["--max-old-space-size=128", ownerFixture],
{ stdio: "ignore" },
);
try {
for (
let attempt = 0;
attempt < 200 && !(await exists(ownerPidFile));
attempt++
)
await delay();
const pid = Number(await readFile(ownerPidFile, "utf8"));
const closed = new Promise((resolve) => owner.once("close", resolve));
owner.kill("SIGKILL");
await closed;
for (let attempt = 0; attempt < 100 && live(pid); attempt++) await delay();
assert.equal(live(pid), false);
report.processes.ownerForcedExitKillsOwnedChild = true;
} finally {
if (owner.exitCode === null && owner.signalCode === null) {
const closed = new Promise((resolve) => owner.once("close", resolve));
owner.kill("SIGKILL");
await closed;
}
}
report.ok = true;
if (process.argv[4] !== undefined)
await writeFile(process.argv[4], `${JSON.stringify(report)}\n`);
process.stdout.write(`${JSON.stringify(report)}\n`);
} catch (cause) {
console.error(
"Native conformance failed",
cause.code ?? cause.name,
cause.constraint ?? "assertion",
);
throw cause;
} finally {
await rm(workspace, { recursive: true, force: true }).catch((cause) =>
console.error("Fixture cleanup failed", cause.code),
);
}
+2
View File
@@ -49,6 +49,8 @@ try {
const packagedPaths = new Set(packageResult.files.map(({ path }) => path));
for (const required of [
"bridge/ghidra/ReaGhidraBridge.java",
"native/windows/build/manifest.json",
"native/windows/build/rea-windows-x64.node",
"dist/main.js",
"dist/cli.js",
"scripts/rea.mjs",
+2 -2
View File
@@ -3,8 +3,8 @@ name: reverse-engineer-anything
description: Reverse engineer native, managed, Electron/JavaScript, packaged, and browser applications with REA. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.
metadata:
version: "24"
tool_count: 116
catalog_digest: "5bb3f994a3c4d0c87a34ff5aab4e28141b5fa6f3a98b5ae7e95686d85d9d983e"
tool_count: 118
catalog_digest: "b4f7e5860d90b029876b58fe7cd4a8041fef1f2add23440e37e90827d808e503"
---
# REA
@@ -9,10 +9,25 @@ cross-references. Addresses and recovered pseudocode are analysis observations,
not original source. Provider unavailability and unsupported metadata remain
unknown rather than false.
Use `binary_session` with its default summary to check the open target, selected
provider, alignment, and recommended remediation. Request the capabilities view
with a family filter and page bounds only when choosing a tool. Request the full
view only for an explicit session-diagnostic need.
Use `binary_session` with no arguments to check the open target, selected
provider, and alignment. Its default `result.tool_availability` includes the
complete tool inventory with availability reasons and remediation. When choosing
a tool, use its entry in that result; `tools/list` retains the complete catalog
when the target or provider state changes.
## DOS MZ with Ghidra
For an admitted DOS MZ target, use `inspect_native_load_image` to check measured
loaded bytes, file mappings, relocations and the entry against the immutable
snapshot. Keep `mismatch` and `unsupported` explicit. Verified import covers the
reported static image, not runtime DOS or PC-98 hardware behavior.
Use `read_bytes` for initialized analysis memory and `address_to_file_offset` to
anchor one observed address to original file bytes. Loader fixups can change a
word; a source offset does not imply byte equality. Complete function body ranges
use inclusive ends and can contain gaps. Do not treat the enclosing span as code.
For packed targets, retain the original and separately derived artifact identities;
decompiling an unpacking stub does not recover the unpacked program.
## Managed PE/CLI
@@ -40,3 +55,12 @@ hosts, with an owned temporary mount directory and cleanup. It needs no approval
flag. Unsupported hosts or mount failures remain explicit limitations; do not
claim child inventory when only root identity is available. Extraction is a
separate filesystem-writing operation.
For headerless DOS COM, explicitly open with `format: "dos-com"` (CLI
`--target-format dos-com`). Inspect the load image before trusting function
analysis: the entry is `0x10100`, file offset zero, with imposed real-mode segment
context. PSP/stack/device state remains unmodeled. See [DOS guide](../../../docs/ghidra-dos.md).
### Function annotations in Ghidra
Use `annotate_native_function` for one function name and/or entry comments, with at least one explicit change. Review its annotation readback and refreshed dossier inline. Changes are atomic and session-scoped; empty comments clear them, omitted fields preserve them. Later MCP calls observe edits until close. CLI `annotate-native-function` returns the updated analysis before discarding the session. Original executable bytes are unchanged; edits invalidate immutable snapshots. Windows P0 does not admit database mutations.
+1 -1
View File
@@ -1,6 +1,6 @@
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { err, ok, type Result } from "../domain/result.js";
import type { AnalysisError } from "../domain/errors.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { AnalysisClient, ExecutionOptions } from "./AnalysisProvider.js";
/** Close one provider client and normalize unexpected adapter rejection. */
@@ -13,7 +13,7 @@ import {
AnalysisCancelledError,
AnalysisOutputError,
AnalysisProtocolError,
} from "../domain/errors.js";
} from "../domain/analysisErrorCore.js";
import { err, ok } from "../domain/result.js";
const provider = { id: "fixture", name: "Fixture", version: "1" };
+2 -2
View File
@@ -6,8 +6,8 @@ import type {
import {
AnalysisCapabilityUnavailableError,
AnalysisOutputError,
type AnalysisError,
} from "../domain/errors.js";
} from "../domain/analysisErrorCore.js";
import { type AnalysisError } from "../domain/analysisErrorBase.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { parseDocuments } from "../domain/hopperValues.js";
import { err, ok, type Result } from "../domain/result.js";
+2 -2
View File
@@ -1,10 +1,10 @@
import type { BinaryTarget } from "../domain/binaryTarget.js";
import type { OfficialToolName } from "../contracts/toolContracts.js";
import type { OfficialToolName } from "../contracts/officialToolContracts.js";
import type { EnhancedToolName } from "../contracts/enhancedInputs.js";
import type { NativeToolName } from "../contracts/nativeToolContracts.js";
import type { ArtifactAnalysisOperation } from "../contracts/artifactToolContracts.js";
import type { ManagedToolName } from "../contracts/managedToolContracts.js";
import type { AnalysisError } from "../domain/errors.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { Result } from "../domain/result.js";
@@ -3,7 +3,7 @@ import {
type AnalysisProfileCommitment,
} from "../domain/analysisProfile.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { AnalysisCancelledError } from "../domain/errors.js";
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import type { AnalysisProviderCandidate } from "./AnalysisProvider.js";
@@ -41,7 +41,8 @@ export const evaluateAnalysisProviderCandidate = async (
if (resolution === ABORTED)
return err(new AnalysisCancelledError("open_binary"));
resolved = resolution;
} catch {
} catch (cause: unknown) {
void cause;
return ok(
rejectedProfile(candidate, status, "Provider profile resolution threw"),
);
@@ -82,7 +83,8 @@ export const evaluateAnalysisProviderCandidate = async (
),
);
return ok({ candidate, status, profile, compatibility });
} catch {
} catch (cause: unknown) {
void cause;
return ok(
rejectedProfile(
candidate,
@@ -15,11 +15,9 @@ import {
} from "./AnalysisProvider.js";
import { createAnalysisProfile } from "../domain/analysisProfile.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import {
ProviderAdapterError,
ProviderSelectionError,
projectAnalysisError,
} from "../domain/errors.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { ProviderSelectionError } from "../domain/providerSelectionError.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { err, ok } from "../domain/result.js";
const DATABASE_TARGET: BinaryTarget = {
+2 -2
View File
@@ -5,12 +5,12 @@ import {
} from "../contracts/providerSelection.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import {
AnalysisCancelledError,
ProviderSelectionError,
type ProviderSelectionFailureReason,
type ProviderSelectionRejection,
} from "../domain/errors.js";
} from "../domain/providerSelectionError.js";
import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import type {
+3 -5
View File
@@ -2,11 +2,9 @@ import type { BinaryTarget } from "../domain/binaryTarget.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { EvidenceBundle } from "../domain/evidenceBundle.js";
import {
EvidenceIntegrityError,
NoBinaryOpenError,
type AnalysisError,
} from "../domain/errors.js";
import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
import { NoBinaryOpenError } from "../domain/configurationErrors.js";
import { type AnalysisError } from "../domain/analysisErrorBase.js";
import { err, ok, type Result } from "../domain/result.js";
import {
analysisQueryId,
+4 -1
View File
@@ -3,7 +3,10 @@ import {
serializeAnalysisSnapshot,
type AnalysisSnapshot,
} from "../domain/analysisSnapshot.js";
import { EvidenceFileError, EvidenceIntegrityError } from "../domain/errors.js";
import {
EvidenceFileError,
EvidenceIntegrityError,
} from "../domain/evidenceErrors.js";
import { err, ok, type Result } from "../domain/result.js";
import { readJsonFile, writeTextFile } from "./JsonFiles.js";
+1 -1
View File
@@ -1,4 +1,4 @@
import type { AnalysisError } from "../domain/errors.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { Evidence } from "../domain/evidence.js";
import {
androidApplicationProjectionInputSchema,
+1 -1
View File
@@ -1,4 +1,4 @@
import type { AnalysisError } from "../domain/errors.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { Evidence } from "../domain/evidence.js";
import {
appleApplicationProjectionInputSchema,
+8 -4
View File
@@ -1,5 +1,6 @@
import { lstat, realpath } from "node:fs/promises";
import { canonicalDigest } from "../domain/comparisonSemantics.js";
import { AsarArtifactReader } from "../artifacts/AsarArtifactReader.js";
import {
ArtifactPathRegistry,
@@ -23,7 +24,6 @@ import {
} from "../domain/artifactGraph.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { scanArtifactInventory } from "./ArtifactInventory.js";
import { digestCanonical } from "./ArtifactGraphConstruction.js";
/** Local extraction input with the output root chosen by the adapter. */
export interface ArtifactExtractionInput {
@@ -171,7 +171,11 @@ const materializeSelection = async ({
await output.commit();
return result;
} catch (cause: unknown) {
if (!readerClosed) await reader.close().catch(() => undefined);
if (!readerClosed)
await reader.close().catch((cause: unknown) => {
// best-effort cleanup: reader close must not mask the extraction failure.
void cause;
});
await output.rollback();
throw cause;
}
@@ -188,14 +192,14 @@ const createExtractionResult = (
selected_occurrence_ids: selected
.map(({ occurrence }) => occurrence.occurrence_id)
.sort((left, right) => left.localeCompare(right)),
files_sha256: digestCanonical(extracted),
files_sha256: canonicalDigest(extracted, "Artifact"),
output_root_alias: "$OUTPUT_ROOT" as const,
};
return artifactExtractionResultSchema.parse({
manifest: inventory.manifest,
extraction_manifest: {
...extractionSemantic,
extraction_id: `aex_${digestCanonical(extractionSemantic)}`,
extraction_id: `aex_${canonicalDigest(extractionSemantic, "Artifact")}`,
},
output_root: input.outputRoot,
artifacts: extracted,
+24 -28
View File
@@ -1,7 +1,4 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { canonicalDigest } from "../domain/comparisonSemantics.js";
import type { ArtifactEntry } from "../artifacts/ArtifactReader.js";
import type {
ArtifactCommand,
@@ -44,7 +41,7 @@ export const createOccurrence = (
path: string,
parent: string | null,
): MutableOccurrence => ({
occurrence_id: `occ_${digestCanonical({ path, kind: entry.kind })}`,
occurrence_id: `occ_${canonicalDigest({ path, kind: entry.kind }, "Artifact")}`,
artifact_id: null,
parent_occurrence_id: parent,
logical_path: path,
@@ -99,7 +96,7 @@ export const materializeDirectoryNodes = (
}))
.sort((left, right) => compareDirectoryChildNames(left.name, right.name));
const node = createArtifactNode({
sha256: digestCanonical({ kind: "directory", children }),
sha256: canonicalDigest({ kind: "directory", children }, "Artifact"),
size: 0,
kind: directory.logical_path.toLowerCase().endsWith(".framework")
? "framework"
@@ -128,13 +125,16 @@ export const createRootNode = (input: {
createArtifactNode({
sha256:
input.digest?.sha256 ??
digestCanonical({
kind: "directory-root",
children: input.occurrences.map(({ logical_path, artifact_id }) => ({
logical_path,
artifact_id,
})),
}),
canonicalDigest(
{
kind: "directory-root",
children: input.occurrences.map(({ logical_path, artifact_id }) => ({
logical_path,
artifact_id,
})),
},
"Artifact",
),
size: input.digest?.bytes ?? 0,
kind:
input.directory ||
@@ -159,7 +159,7 @@ export const createArtifactNode = (input: {
readonly contentState: ArtifactNode["content_state"];
readonly limitations?: readonly string[];
}): ArtifactNode => ({
artifact_id: `art_${digestCanonical({ sha256: input.sha256 })}`,
artifact_id: `art_${canonicalDigest({ sha256: input.sha256 }, "Artifact")}`,
kind: input.kind,
format: input.format,
sha256: input.sha256,
@@ -175,7 +175,7 @@ export const rootOccurrenceFor = (
node: ArtifactNode,
declaredSize: number,
): MutableOccurrence => ({
occurrence_id: `occ_${digestCanonical({ root: node.artifact_id })}`,
occurrence_id: `occ_${canonicalDigest({ root: node.artifact_id }, "Artifact")}`,
artifact_id: node.artifact_id,
parent_occurrence_id: null,
logical_path: ".",
@@ -197,11 +197,14 @@ export const rekeyOccurrences = (
for (const occurrence of occurrences)
replacements.set(
occurrence.occurrence_id,
`occ_${digestCanonical({
root_artifact_id: rootArtifactId,
logical_path: occurrence.logical_path,
entry_kind: occurrence.entry_kind,
})}`,
`occ_${canonicalDigest(
{
root_artifact_id: rootArtifactId,
logical_path: occurrence.logical_path,
entry_kind: occurrence.entry_kind,
},
"Artifact",
)}`,
);
for (const occurrence of occurrences) {
occurrence.occurrence_id =
@@ -245,7 +248,7 @@ export const createArtifactEdges = (
logical_path: occurrence.logical_path,
};
edges.push({
edge_id: `edge_${digestCanonical(semantic)}`,
edge_id: `edge_${canonicalDigest(semantic, "Artifact")}`,
...semantic,
producer: occurrence.entry_kind === "slice" ? (producer ?? null) : null,
ordinal: edges.length,
@@ -356,13 +359,6 @@ export const classifyArtifactContent = (
return byPath;
};
export const digestCanonical = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError("Artifact value is not canonical JSON");
return createHash("sha256").update(encoded).digest("hex");
};
const relationFor = (path: string): ArtifactEdge["relation"] => {
const lower = path.toLowerCase();
if (lower.endsWith(".map")) return "maps-source";
@@ -15,13 +15,13 @@ import {
import {
createArtifactEdges,
createRootNode,
digestCanonical,
indexOccurrencesByPath,
materializeDirectoryNodes,
rekeyOccurrences,
rootOccurrenceFor,
type MutableOccurrence,
} from "../ArtifactGraphConstruction.js";
import { canonicalDigest } from "../../domain/comparisonSemantics.js";
import { classifyRoot } from "./classify.js";
import { hashReadable, type HashResult } from "./hash.js";
import { createReader, inventoryLimitations } from "./reader.js";
@@ -125,12 +125,15 @@ const buildInventorySnapshot = async (
await verifyRootDigest(path, rootDigest, signal);
const graphSha256 = digestCanonical({
nodes: orderedNodes,
occurrences: orderedOccurrences,
edges: orderedEdges,
integrity_contradictions: integrityContradictions,
});
const graphSha256 = canonicalDigest(
{
nodes: orderedNodes,
occurrences: orderedOccurrences,
edges: orderedEdges,
integrity_contradictions: integrityContradictions,
},
"Artifact",
);
const manifest = buildManifest({
rootNode,
graphSha256,
@@ -168,12 +171,15 @@ const buildIntegrityContradictions = (
: occurrenceById.get(occurrence.parent_occurrence_id);
const parentArtifactId = parent?.artifact_id ?? rootNode.artifact_id;
return {
contradiction_id: `ic_${digestCanonical({
root_artifact_id: rootNode.artifact_id,
logical_path: contradiction.logicalPath,
declared_sha256: contradiction.declaredSha256,
observed_sha256: contradiction.observedSha256,
})}`,
contradiction_id: `ic_${canonicalDigest(
{
root_artifact_id: rootNode.artifact_id,
logical_path: contradiction.logicalPath,
declared_sha256: contradiction.declaredSha256,
observed_sha256: contradiction.observedSha256,
},
"Artifact",
)}`,
occurrence_id: occurrence.occurrence_id,
parent_artifact_id: parentArtifactId,
logical_path: contradiction.logicalPath,
@@ -235,10 +241,13 @@ const buildManifest = ({
readonly orderedEdges: readonly { edge_id: string }[];
}): ArtifactInventoryResult["manifest"] =>
artifactInventoryResultSchema.shape.manifest.parse({
manifest_id: `agm_${digestCanonical({
root_artifact_id: rootNode.artifact_id,
graph_sha256: graphSha256,
})}`,
manifest_id: `agm_${canonicalDigest(
{
root_artifact_id: rootNode.artifact_id,
graph_sha256: graphSha256,
},
"Artifact",
)}`,
root_artifact_id: rootNode.artifact_id,
root_sha256: rootNode.sha256,
root_format: rootNode.format,
+8 -6
View File
@@ -5,10 +5,8 @@ import {
analysisProfilesEqual,
type AnalysisProfileCommitment,
} from "../domain/analysisProfile.js";
import {
AnalysisCancelledError,
type AnalysisError,
} from "../domain/errors.js";
import { AnalysisCancelledError } 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";
import { createEvidence } from "../domain/evidence.js";
@@ -422,11 +420,15 @@ export class BinarySession
for (const listener of this.#availabilityListeners) {
try {
const notification = listener();
if (notification !== undefined)
if (notification !== undefined) {
// best-effort cleanup: async observer notifications must not reject
// unhandled; state transitions and other listeners continue.
void notification.catch(() => undefined);
} catch {
}
} catch (cause: unknown) {
// External observers are best-effort notifications. Contain only the
// callback failure so state transitions and other listeners continue.
void cause;
}
}
}
+4 -6
View File
@@ -1,11 +1,9 @@
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import {
AnalysisCapabilityUnavailableError,
NoBinaryOpenError,
ProviderAdapterError,
type AnalysisError,
} from "../domain/errors.js";
import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";
import { NoBinaryOpenError } from "../domain/configurationErrors.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { type AnalysisError } from "../domain/analysisErrorBase.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { EvidenceSubjectTarget } from "../domain/evidence.js";
import { err, ok, type Result } from "../domain/result.js";
+5 -4
View File
@@ -1,3 +1,4 @@
import type { ExecutableFormatHint } from "../domain/dosCom.js";
import type { AnalysisProviderSelector } from "../contracts/providerSelection.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import {
@@ -8,10 +9,8 @@ import {
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
import { parseBinaryTarget } from "./BinaryTargetResolver.js";
import { type BinaryTarget } from "../domain/binaryTarget.js";
import {
EvidenceIntegrityError,
type AnalysisError,
} from "../domain/errors.js";
import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
import { type AnalysisError } from "../domain/analysisErrorBase.js";
import { err, type Result } from "../domain/result.js";
import type { SessionProviderRoute } from "./SessionProviderRouter.js";
import { SessionProviderRouter } from "./SessionProviderRouter.js";
@@ -19,6 +18,7 @@ import { SessionProviderRouter } from "./SessionProviderRouter.js";
export interface BinarySessionOpenOptions {
readonly signal?: AbortSignal;
readonly targetKind?: BinaryTarget["kind"];
readonly formatHint?: ExecutableFormatHint;
readonly snapshot?: AnalysisSnapshot;
readonly providerId?: AnalysisProviderSelector;
}
@@ -56,6 +56,7 @@ export const resolveSessionOpen = async (
process.cwd(),
process.arch,
options.targetKind,
options.formatHint,
);
if (!parsed.ok) return parsed;
const target = parsed.value;
+5 -5
View File
@@ -1,3 +1,4 @@
import type { ExecutableFormatHint } from "../domain/dosCom.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { Evidence } from "../domain/evidence.js";
@@ -5,11 +6,9 @@ import type { EvidenceBundle } from "../domain/evidenceBundle.js";
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { AnalysisProviderSelector } from "../contracts/providerSelection.js";
import type {
AnalysisError,
EvidenceIntegrityError,
UnknownRegistryError,
} from "../domain/errors.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
import type { UnknownRegistryError } from "../domain/unknownRegistryError.js";
import type { Result } from "../domain/result.js";
import type {
RecordUnknownInput,
@@ -31,6 +30,7 @@ export interface BinarySessionPort extends AnalysisOperationPort {
options?: {
readonly signal?: AbortSignal;
readonly targetKind?: BinaryTarget["kind"];
readonly formatHint?: ExecutableFormatHint;
readonly snapshot?: AnalysisSnapshot;
readonly providerId?: AnalysisProviderSelector;
},
+9 -7
View File
@@ -4,11 +4,9 @@ import type { BinaryTarget } from "../domain/binaryTarget.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import type { EvidenceBundle } from "../domain/evidenceBundle.js";
import { evidenceBundleForTarget } from "../domain/evidenceBundle.js";
import {
EvidenceIntegrityError,
type AnalysisError,
type UnknownRegistryError,
} from "../domain/errors.js";
import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
import { type AnalysisError } from "../domain/analysisErrorBase.js";
import { type UnknownRegistryError } from "../domain/unknownRegistryError.js";
import type {
RecordUnknownInput,
ResidualUnknown,
@@ -188,10 +186,14 @@ export abstract class BinarySessionRecords {
try {
const notification = listener();
if (notification !== undefined)
void notification.catch(() => undefined);
} catch {
void notification.catch((cause: unknown) => {
// best-effort cleanup: async observer notifications must not reject unhandled.
void cause;
});
} catch (cause: unknown) {
// External resource observers are best-effort; one callback must not
// make a committed evidence mutation appear to fail.
void cause;
}
}
}
+31 -6
View File
@@ -13,9 +13,13 @@ import { extname, isAbsolute, join, resolve } from "node:path";
import { promisify } from "node:util";
import { isPathWithinRoot } from "../domain/localPath.js";
import { BinaryTargetError } from "../domain/errors.js";
import { BinaryTargetError } from "../domain/configurationErrors.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import { err, ok, type Result } from "../domain/result.js";
import {
validateDosComLength,
type ExecutableFormatHint,
} from "../domain/dosCom.js";
import { mzWindowsHeaderOffset } from "../domain/dosMz.js";
import {
hasZipSignature,
@@ -40,6 +44,7 @@ export const parseBinaryTarget = async (
cwd = process.cwd(),
hostArchitecture: NodeJS.Architecture = process.arch,
targetKind?: BinaryTarget["kind"],
formatHint?: ExecutableFormatHint,
): Promise<Result<BinaryTarget, BinaryTargetError>> => {
const candidate = isAbsolute(input) ? input : resolve(cwd, input);
try {
@@ -52,13 +57,33 @@ export const parseBinaryTarget = async (
try {
if (!(await handle.stat()).isFile())
return err(new BinaryTargetError(path, "target is not a regular file"));
if (formatHint === "dos-com") {
if (targetKind !== undefined && targetKind !== "executable")
return err(
new BinaryTargetError(
path,
"DOS COM format requires an executable target kind",
),
);
const length = validateDosComLength((await handle.stat()).size);
if (!length.ok) return err(new BinaryTargetError(path, length.error));
return ok({
path,
sourcePath: canonical,
sha256: await sha256Handle(handle),
kind: "executable",
format: "dos-com",
architecture: "x86",
availableArchitectures: ["x86"],
});
}
if (
targetKind === "database" ||
(targetKind === undefined && path.toLowerCase().endsWith(".hop"))
)
return ok({
path,
sourcePath: canonical,
sourcePath: process.platform === "win32" ? candidate : canonical,
sha256: await sha256Handle(handle),
kind: "database",
format: "analysis-database",
@@ -67,7 +92,7 @@ export const parseBinaryTarget = async (
if (artifactFormat !== undefined) {
const identity = {
path,
sourcePath: canonical,
sourcePath: process.platform === "win32" ? candidate : canonical,
sha256: await sha256Handle(handle),
};
return isArchiveFormat(artifactFormat)
@@ -78,7 +103,7 @@ export const parseBinaryTarget = async (
if (!detected.ok) return err(new BinaryTargetError(path, detected.error));
return ok({
path,
sourcePath: canonical,
sourcePath: process.platform === "win32" ? candidate : canonical,
sha256: await sha256Handle(handle),
kind: "executable",
...detected.value,
@@ -126,7 +151,7 @@ const detectArtifactFormat = async (
): Promise<
| Exclude<
BinaryTarget["format"],
"analysis-database" | "mach-o" | "elf" | "pe" | "dos-mz"
"analysis-database" | "mach-o" | "elf" | "pe" | "dos-mz" | "dos-com"
>
| undefined
> => {
@@ -168,7 +193,7 @@ const namedArtifactFormat = (
const isArchiveFormat = (
format: Exclude<
BinaryTarget["format"],
"analysis-database" | "mach-o" | "elf" | "pe" | "dos-mz"
"analysis-database" | "mach-o" | "elf" | "pe" | "dos-mz" | "dos-com"
>,
): format is Extract<BinaryTarget, { kind: "archive" }>["format"] =>
["zip", "ipa", "apk", "msix", "appx", "asar", "dmg", "pkg"].includes(format);
+1 -1
View File
@@ -1,4 +1,4 @@
import type { AnalysisError } from "../domain/errors.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type {
BrowserTargetList,
InspectWebPageInput,
+2 -4
View File
@@ -11,10 +11,8 @@ import type {
CaptureWebScreenshotInput,
CompareWebScreenshotsInput,
} from "../domain/webScreenshot.js";
import {
AnalysisCapabilityUnavailableError,
type AnalysisError,
} from "../domain/errors.js";
import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";
import { type AnalysisError } from "../domain/analysisErrorBase.js";
import { err, ok, type Result } from "../domain/result.js";
import type { ExecutionOptions } from "./AnalysisProvider.js";
import type { BrowserObservationPort } from "./BrowserObservationPort.js";
@@ -1,5 +1,5 @@
import type { ExecutionOptions, ProviderIdentity } from "./AnalysisProvider.js";
import type { AnalysisError } from "../domain/errors.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { BrowserScenario } from "../domain/browserScenario.js";
import type { BrowserScenarioCapture } from "../domain/browserScenarioCapture.js";
import type { Result } from "../domain/result.js";
@@ -1,10 +1,8 @@
import type { ExecutionOptions } from "./AnalysisProvider.js";
import type { BrowserScenarioCapturePort } from "./BrowserScenarioCapturePort.js";
import { createBrowserScenarioEvidence } from "./BrowserScenarioEvidence.js";
import {
AnalysisCapabilityUnavailableError,
type AnalysisError,
} from "../domain/errors.js";
import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";
import { type AnalysisError } from "../domain/analysisErrorBase.js";
import type { Evidence } from "../domain/evidence.js";
import type { BrowserScenario } from "../domain/browserScenario.js";
import { err, type Result } from "../domain/result.js";
+2 -2
View File
@@ -1,3 +1,4 @@
import { canonicalDigest } from "../domain/comparisonSemantics.js";
import type { ProviderIdentity } from "./AnalysisProvider.js";
import type { BrowserScenario } from "../domain/browserScenario.js";
import type { BrowserScenarioCapture } from "../domain/browserScenarioCapture.js";
@@ -8,12 +9,11 @@ import {
type EvidenceObservation,
} from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { digestCanonicalJson } from "../domain/browserScenarioNormalization.js";
const browserScenarioParameters = (
scenario: BrowserScenario,
): EvidenceObservation["parameters"] => ({
scenario_sha256: digestCanonicalJson(scenario),
scenario_sha256: canonicalDigest(scenario, "Browser scenario"),
browser_mode: scenario.browser.mode,
...(scenario.browser.mode === "launch"
? { browser_headless: scenario.browser.headless }
+2 -1
View File
@@ -1,5 +1,6 @@
import type { AnalysisOperation } from "./AnalysisProvider.js";
import { projectAnalysisError, type AnalysisError } from "../domain/errors.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { type AnalysisError } from "../domain/analysisErrorBase.js";
import { parseRelatedAddresses } from "../domain/hopperValues.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { ok, type Result } from "../domain/result.js";
+3 -1
View File
@@ -44,7 +44,9 @@ export const resolveClientConfigTransactionPath = async (
return targetStats.isFile?.() === true && targetStats.uid === currentUid
? canonicalPath
: undefined;
} catch {
} catch (cause: unknown) {
// best-effort cleanup: unreadable or vanishing config paths mean no registration.
void cause;
return undefined;
}
};
@@ -150,6 +150,14 @@ export const clientRegistrationEntry = (
tools: ["*"],
...(Object.keys(environment).length === 0 ? {} : { env: environment }),
};
case "commandcode":
return {
transport: "stdio",
enabled: true,
command: executable,
args,
...(Object.keys(environment).length === 0 ? {} : { env: environment }),
};
default:
return {
command: executable,
+8 -1
View File
@@ -47,6 +47,7 @@ const registrationSchema = z
args: z.array(z.string()).default([]),
startup_timeout_sec: z.number().positive().optional(),
type: z.string().optional(),
transport: z.string().optional(),
tools: z.array(z.string()).optional(),
disabled: z.boolean().optional(),
enabled: z.boolean().optional(),
@@ -152,6 +153,8 @@ const registrationAligned = (
JSON.stringify(registration.tools) !== JSON.stringify(["*"]))
)
return false;
if (client.format === "commandcode" && registration.transport !== "stdio")
return false;
if (
command.length === 4 &&
command[0] === "npx" &&
@@ -193,6 +196,8 @@ const parseRegistration = (
registration.type !== "stdio"
)
throw new TypeError("Expected an stdio registration");
if (client.format === "commandcode" && registration.transport !== "stdio")
throw new TypeError("Expected an stdio registration");
return registration;
};
@@ -226,7 +231,9 @@ const exists = async (path: string | undefined): Promise<boolean> => {
try {
await access(path);
return true;
} catch {
} catch (cause: unknown) {
// best-effort cleanup: optional registration probing; absence means unregistered.
void cause;
return false;
}
};
+1 -1
View File
@@ -1,4 +1,4 @@
import { AnalysisCapabilityUnavailableError } from "../domain/errors.js";
import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";
import { err, ok } from "../domain/result.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
+27 -6
View File
@@ -1,3 +1,4 @@
import type { ExecutableFormatHint } from "../domain/dosCom.js";
import { parseConfig } from "../config.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { EnhancedTools } from "./EnhancedTools.js";
@@ -11,11 +12,9 @@ import {
isManagedToolName,
type ManagedToolName,
} from "../contracts/managedToolContracts.js";
import {
EvidenceIntegrityError,
projectAnalysisError,
type AnalysisError,
} from "../domain/errors.js";
import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { type AnalysisError } from "../domain/analysisErrorBase.js";
import { access } from "node:fs/promises";
import {
readAnalysisSnapshot,
@@ -44,6 +43,10 @@ export {
} from "./DirectAnalysisStatus.js";
type DirectAnalysisTool =
| "annotate_native_function"
| "inspect_native_load_image"
| "read_bytes"
| "address_to_file_offset"
| "binary_overview"
| "procedure_pseudo_code"
| "read_function_instructions"
@@ -74,6 +77,7 @@ export const runDirectAnalysis = async (
readonly snapshotPath?: string | undefined;
readonly signal?: AbortSignal;
readonly providerId?: AnalysisProviderSelector;
readonly formatHint?: ExecutableFormatHint;
} = {},
): Promise<JsonValue> =>
withProcessCancellation(options.signal, (signal) =>
@@ -81,6 +85,9 @@ export const runDirectAnalysis = async (
logger: options.logger ?? silentLogger,
snapshotPath: options.snapshotPath,
signal,
...(options.formatHint === undefined
? {}
: { formatHint: options.formatHint }),
...(options.providerId === undefined
? {}
: { providerId: options.providerId }),
@@ -155,6 +162,7 @@ const runAnalysis = async (
readonly snapshotPath: string | undefined;
readonly signal: AbortSignal;
readonly providerId?: AnalysisProviderSelector;
readonly formatHint?: ExecutableFormatHint;
/**
* Environment the configuration is read from. Defaults to the process
* environment so existing callers are unchanged, but a caller may supply
@@ -173,11 +181,17 @@ const runAnalysis = async (
const prepared = await prepareSnapshot({
path,
snapshotPath,
...(options.formatHint === undefined
? {}
: { formatHint: options.formatHint }),
});
if (!prepared.ok) return cliError(prepared.error);
const { snapshot } = prepared.value;
const opened = await session.open(path, {
signal,
...(options.formatHint === undefined
? {}
: { formatHint: options.formatHint }),
...(snapshot === undefined ? {} : { snapshot }),
...(options.providerId === undefined
? {}
@@ -319,6 +333,7 @@ const withProcessCancellation = async <Value>(
const prepareSnapshot = async (options: {
readonly path: string;
readonly formatHint?: ExecutableFormatHint;
readonly snapshotPath: string | undefined;
}): Promise<
Result<{ readonly snapshot?: AnalysisSnapshot }, AnalysisError>
@@ -328,7 +343,13 @@ const prepareSnapshot = async (options: {
return ok({});
const loaded = await readAnalysisSnapshot(snapshotPath);
if (!loaded.ok) return loaded;
const target = await parseBinaryTarget(path);
const target = await parseBinaryTarget(
path,
process.cwd(),
process.arch,
undefined,
options.formatHint,
);
if (!target.ok) return target;
if (!snapshotMatchesTarget(loaded.value.target, target.value))
return err(
+1 -1
View File
@@ -1,5 +1,5 @@
import { parseConfig } from "../config.js";
import { projectAnalysisError } from "../domain/errors.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
import { createServerIdentity } from "../serverIdentity.js";
import { silentLogger, type Logger } from "../logger.js";
+15 -1
View File
@@ -19,13 +19,27 @@ describe("doctor", () => {
result.checks.map(({ name, remediation }) => [name, remediation]),
),
).toEqual({
node: "Install Node.js 22.19+ or 24.11+.",
node: "Install Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+.",
host: "REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, and the experimental Windows x64 Ghidra P0 boundary.",
hopper: "Run rea setup to install Hopper, or set HOPPER_LAUNCHER_PATH.",
target: "Supply a readable local app or program path.",
});
});
it("reports Node 25 as unsupported", async () => {
const result = await runDoctor(undefined, host({ nodeVersion: "25.1.0" }));
expect(result.healthy).toBe(false);
expect(result.checks).toContainEqual(
expect.objectContaining({
name: "node",
ok: false,
detail: "25.1.0",
classification: "missing_dependency",
}),
);
});
it.each(["11.7", undefined])(
"rejects unsupported macOS version %s",
async (version) => {
+22 -8
View File
@@ -63,7 +63,8 @@ export interface DoctorProviderInspection {
readonly configured: boolean;
readonly available: boolean;
readonly providerVersion: string | null;
/** Exact non-secret variables safe to persist in an approved registration. */
/** Adapter-validated non-secret settings, independent of runtime readiness.
* Invalid installations publish no settings. */
readonly registrationEnvironment: Readonly<Record<string, string>>;
readonly checks: readonly DoctorProviderCheck[];
}
@@ -353,7 +354,9 @@ export const systemDoctorHost = (
)
).stdout.trim();
return `${prefix}/Hopper Disassembler.app/Contents/MacOS/hopper`;
} catch {
} catch (cause: unknown) {
// best-effort cleanup: optional Homebrew probing; absence means uninstalled.
void cause;
return undefined;
}
});
@@ -373,7 +376,9 @@ export const systemDoctorHost = (
})
).stdout,
);
} catch {
} catch (cause: unknown) {
// best-effort cleanup: optional version probing; failure means unavailable.
void cause;
return undefined;
}
},
@@ -385,7 +390,9 @@ export const systemDoctorHost = (
(await hostExecFileOutput(command, arguments_, commandEnvironment))
.stdout,
);
} catch {
} catch (cause: unknown) {
// best-effort cleanup: optional path probing; failure means none found.
void cause;
return [];
}
},
@@ -404,7 +411,9 @@ const readMacosVersion = async (
): Promise<string | undefined> => {
try {
return (await run("sw_vers", ["-productVersion"], options)).stdout.trim();
} catch {
} catch (cause: unknown) {
// best-effort cleanup: optional OS version probing; failure means unknown.
void cause;
return undefined;
}
};
@@ -420,7 +429,9 @@ const executableAvailable = async (
if (platform !== "linux") return true;
const linked = await run("ldd", [path], options);
return linuxSharedLibrariesAvailable(`${linked.stdout}\n${linked.stderr}`);
} catch {
} catch (cause: unknown) {
// best-effort cleanup: optional executable probing; failure means unavailable.
void cause;
return false;
}
};
@@ -444,8 +455,9 @@ const manualHopperPaths = async (
if (entry.isDirectory() && /^Hopper.*\.app$/i.test(entry.name))
paths.push(join(root, entry.name, "Contents/MacOS/hopper"));
}
} catch {
} catch (cause: unknown) {
// A missing or unreadable optional application directory is not fatal.
void cause;
}
}
return paths;
@@ -471,7 +483,9 @@ const installedSkillIdentity = async (
/^\s{2}catalog_digest:\s*"([a-f0-9]{64})"\s*$/mu.exec(content)?.[1] ??
null,
};
} catch {
} catch (cause: unknown) {
// best-effort cleanup: optional skill probing; failure means unknown.
void cause;
return undefined;
}
};
+1 -1
View File
@@ -92,7 +92,7 @@ export const doctorHealthy = (
const nodeCheck = (host: DoctorHost): DoctorCheck =>
check("node", supportsNodeVersion(host.nodeVersion), host.nodeVersion, {
remediation: "Install Node.js 22.19+ or 24.11+.",
remediation: "Install Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+.",
classification: "missing_dependency",
});
+1 -3
View File
@@ -1,3 +1,4 @@
import { uniqueSorted } from "../domain/canonicalOrdering.js";
import type {
ClientRegistrationStatus,
UnhealthyClientRegistrationStatus,
@@ -175,8 +176,5 @@ const selectedSkillCheck = (
: { remediation: "Run rea setup to update the installed REA skill." }),
};
const uniqueSorted = (values: readonly string[]): readonly string[] =>
[...new Set(values)].sort((left, right) => left.localeCompare(right));
const doctorProviderCheckName = (providerId: string, name: string): boolean =>
name === providerId || name.startsWith(`${providerId}-`);
+5 -2
View File
@@ -1,3 +1,4 @@
import { canonicalDigest } from "../domain/comparisonSemantics.js";
import type { ProviderIdentity } from "./AnalysisProvider.js";
import type { Evidence, EvidenceObservation } from "../domain/evidence.js";
import { createEvidence } from "../domain/evidence.js";
@@ -6,7 +7,6 @@ import type {
ElectronActiveObservationResult,
} from "../domain/electronActiveObservation.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { digestCanonicalJson } from "../domain/browserScenarioNormalization.js";
type CanonicalElectronActiveObservationInput =
ElectronActiveObservationInput & {
@@ -52,5 +52,8 @@ const parameters = (
input: CanonicalElectronActiveObservationInput,
): EvidenceObservation["parameters"] => ({
...scenarioProjection(input),
scenario_sha256: digestCanonicalJson(scenarioProjection(input)),
scenario_sha256: canonicalDigest(
scenarioProjection(input),
"Browser scenario",
),
});
@@ -1,5 +1,5 @@
import type { ExecutionOptions, ProviderIdentity } from "./AnalysisProvider.js";
import type { AnalysisError } from "../domain/errors.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type {
ElectronActiveObservationInput,
ElectronActiveObservationResult,
@@ -6,8 +6,8 @@ import type { ElectronActiveObservationPort } from "./ElectronActiveObservationP
import {
AnalysisCapabilityUnavailableError,
AnalysisInputError,
type AnalysisError,
} from "../domain/errors.js";
} from "../domain/analysisErrorCore.js";
import { type AnalysisError } from "../domain/analysisErrorBase.js";
import type { Evidence } from "../domain/evidence.js";
import type { ElectronActiveObservationInput } from "../domain/electronActiveObservation.js";
import { err, type Result } from "../domain/result.js";

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