Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a6de554e2a | ||
|
|
1a322ab75b | ||
|
|
9d8e42bdd6 | ||
|
|
d28b41ea4e | ||
|
|
e8491e023a | ||
|
|
097f0d54af | ||
|
|
e4ac7bbfc2 | ||
|
|
0b7fc40eee | ||
|
|
7a0140b4aa | ||
|
|
9b3e59804d | ||
|
|
1769417001 | ||
|
|
898d5096f9 | ||
|
|
38539a2f4a | ||
|
|
23d50ea3be | ||
|
|
7c207c7951 | ||
|
|
d3e83b0899 | ||
|
|
29d2624b34 | ||
|
|
fa9a7e5ec0 | ||
|
|
efbc25fbea | ||
|
|
ea40f717b2 |
@@ -2,7 +2,7 @@
|
||||
name: reverse-engineer-anything
|
||||
description: Reverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets 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: "38"
|
||||
version: "39"
|
||||
---
|
||||
|
||||
# REA
|
||||
|
||||
@@ -9,7 +9,10 @@ provenance; inputs and recovered code are never executed. Recovery requires a
|
||||
caller-supplied Wakaru on Linux x64; see [the recovery guide](https://github.com/morluto/rea/blob/main/docs/javascript-recovery.md).
|
||||
|
||||
Use `analyze_javascript_application` directly on the operator-supplied ASAR or
|
||||
extracted tree. When size is unknown or large and the connected schema advertises
|
||||
extracted tree. Exact `#alias` specifiers resolve through the importer's
|
||||
enclosing package `imports` map to package-local files; nested `node_modules`
|
||||
packages use their own map. Wildcard, recursive, and external-package import
|
||||
targets stay unresolved with that limitation. When size is unknown or large and the connected schema advertises
|
||||
`detail`, request `detail: "summary"`. This returns an `inspect_analysis_view`
|
||||
Evidence record with a distinct ID and a `normalized_result.parent_evidence_id`
|
||||
for the complete retained application analysis. Source-map contents are part of
|
||||
|
||||
@@ -150,6 +150,13 @@ For headerless DOS COM, explicitly open with `format: "dos-com"` (CLI
|
||||
analysis: the entry is `0x10100`, file offset zero, with imposed real-mode segment
|
||||
context. PSP/stack/device state remains unmodeled. See [DOS guide](https://github.com/morluto/rea/blob/main/docs/ghidra-dos.md).
|
||||
|
||||
For other headerless images (embedded firmware without ELF/Mach-O/PE/MZ
|
||||
headers), open with `format: "raw-binary"`, `architecture` (`x86`, `x86_64`,
|
||||
`arm`, or `arm64`), and `entry_point` (`0x` hex). File offset 0 is mapped at
|
||||
that address. Hopper and IDA refuse this interpretation; Ghidra uses
|
||||
`BinaryLoader` with a little-endian generic language. Big-endian, Thumb-only,
|
||||
and Cortex-M variants are unsupported. See [raw binary guide](https://github.com/morluto/rea/blob/main/docs/raw-binary.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. For naming only, `set_address_name` / `set_addresses_names` also work with Ghidra: they name function entries or data addresses (primary labels) and return compact per-address success booleans instead of a dossier.
|
||||
|
||||
@@ -126,6 +126,20 @@ class ReaJadxBridge {
|
||||
return result;
|
||||
}
|
||||
|
||||
private JadxSession.SmartCode methodBody(JadxSession current, ClassSnapshot cls,
|
||||
MethodSnapshot selected, JavaMethod method) {
|
||||
if (!selected.shortId().equals("<clinit>()V"))
|
||||
return current.getMethodBodySmart(method, current.getMaxSourceBytes(), true);
|
||||
// Java code generation can fold all or part of <clinit> into field declarations.
|
||||
// Its method text cannot establish coverage, even when a static block remains.
|
||||
JadxSession.MethodSmali smali = current.getMethodSmali(cls.node(), method.getName());
|
||||
if (!smali.getFound() || smali.getBlocks().size() != 1)
|
||||
throw new IllegalArgumentException("Static initializer disassembly requires one exact method: " + selected.shortId());
|
||||
return new JadxSession.SmartCode(
|
||||
TextUtilKt.truncateToBytes(smali.getBlocks().get(0), current.getMaxSourceBytes()),
|
||||
"smali", true, List.of("static_initializer_disassembly"));
|
||||
}
|
||||
|
||||
private CallToolResult handle(String name, JsonObject args) {
|
||||
if (name.equals("rea_jvm_status")) return json(Map.of(
|
||||
"engine_reported_version", BuildInfo.VERSION,
|
||||
@@ -150,7 +164,7 @@ class ReaJadxBridge {
|
||||
int index = integer(args, "overload_index", 0);
|
||||
if (index >= overloads.size()) throw new InputFailure("overload_index", "overload_index out of range: " + index);
|
||||
JavaMethod method = method(cls, overloads.get(index));
|
||||
JadxSession.SmartCode code = current.getMethodBodySmart(method, current.getMaxSourceBytes(), true);
|
||||
JadxSession.SmartCode code = methodBody(current, cls, overloads.get(index), method);
|
||||
return json(Map.of("class_name", cls.summary().get("full_name"),
|
||||
"method_name", overloads.get(index).name(), "full_name", method.getFullName(),
|
||||
"overload_index", index, "overload_count", overloads.size(),
|
||||
@@ -211,7 +225,7 @@ class ReaJadxBridge {
|
||||
String description = switch (name) {
|
||||
case "list_classes" -> "Indexed pages of all top-level class names, with offset and limit.";
|
||||
case "get_class_summary" -> "Parsed member metadata for one exact class name; no source generation.";
|
||||
case "get_method_body" -> "Source for an exact class and stable same-name overload index, with smali fallback.";
|
||||
case "get_method_body" -> "Source for an exact class and stable same-name overload index; static initializers use smali to preserve folded field initialization.";
|
||||
default -> "Complete static references to an exact class or unique method; source lines are unresolved.";
|
||||
};
|
||||
Tool narrowed = new Tool(name, new ToolSchema(null, new JsonObject(properties),
|
||||
|
||||
@@ -182,10 +182,17 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
}
|
||||
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 (currentProgram.getExecutableFormat().equals("Raw Binary")) {
|
||||
boolean dosCom = currentProgram.getLanguageID().getIdAsString()
|
||||
.equals("x86:LE:16:Real Mode");
|
||||
String preparation = dosCom ? "REA DOS COM prepared" : "REA raw binary prepared";
|
||||
if (!currentProgram.getOptions(ghidra.program.model.listing.Program.PROGRAM_INFO)
|
||||
.getBoolean(preparation, false)) {
|
||||
throw new IllegalStateException(
|
||||
dosCom ? "REA DOS COM entry/context preparation failed" :
|
||||
"REA raw binary entry preparation failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
if (!Application.getApplicationVersion().equals(descriptor.providerVersion)) {
|
||||
throw new IllegalStateException("Ghidra provider version does not match the session");
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import ghidra.app.script.GhidraScript;
|
||||
import ghidra.program.model.address.Address;
|
||||
import ghidra.program.model.listing.Program;
|
||||
|
||||
/** Seed the caller-supplied raw-binary entry before default auto-analysis. */
|
||||
public final class ReaGhidraPrepareRaw extends GhidraScript {
|
||||
@Override
|
||||
public void run() throws Exception {
|
||||
String[] arguments = getScriptArgs();
|
||||
if (arguments.length != 2) {
|
||||
throw new IllegalArgumentException(
|
||||
"Raw binary preparation requires the committed language and entry address"
|
||||
);
|
||||
}
|
||||
String expectedLanguage = arguments[0];
|
||||
String entryHex = arguments[1];
|
||||
if (!currentProgram.getLanguageID().getIdAsString().equals(expectedLanguage) ||
|
||||
!currentProgram.getExecutableFormat().equals("Raw Binary")) {
|
||||
throw new IllegalArgumentException(
|
||||
"Raw binary preparation requires the committed language and BinaryLoader import"
|
||||
);
|
||||
}
|
||||
Address entry = currentProgram.getAddressFactory().getDefaultAddressSpace().getAddress(entryHex);
|
||||
Address start = currentProgram.getMinAddress();
|
||||
if (entry == null || !entry.equals(start)) {
|
||||
throw new IllegalArgumentException(
|
||||
"Raw binary import must map file offset 0 at the caller-supplied entry"
|
||||
);
|
||||
}
|
||||
addEntryPoint(entry);
|
||||
if (!disassemble(entry) || createFunction(entry, "entry") == null) {
|
||||
throw new IllegalStateException("Raw binary entry cannot be decoded as a function");
|
||||
}
|
||||
currentProgram.getOptions(Program.PROGRAM_INFO).setBoolean("REA raw binary prepared", true);
|
||||
}
|
||||
}
|
||||
@@ -54,6 +54,7 @@ export default defineConfig({
|
||||
{ text: "IDA", link: "/ida-provider" },
|
||||
{ text: "Ghidra on Windows", link: "/windows-ghidra-p0" },
|
||||
{ text: "Ghidra DOS analysis", link: "/ghidra-dos" },
|
||||
{ text: "Ghidra raw binary", link: "/raw-binary" },
|
||||
{ text: "Ghidra NativeAOT", link: "/ghidra-nativeaot" },
|
||||
{ text: "Ghidra semantics", link: "/ghidra-provider" },
|
||||
],
|
||||
|
||||
@@ -94,6 +94,12 @@ fallback for an overloaded method instead of attributing all bodies to one
|
||||
selected overload. Native/abstract methods with no decompiled body report
|
||||
`body_status: "not_available"` without inferring which implementation flag caused it.
|
||||
|
||||
Static initializers (`<clinit>`) return smali with the
|
||||
`static_initializer_disassembly` marker. Java decompilation can move their
|
||||
instructions into field declarations, leaving an empty or incomplete method
|
||||
body. The selected method's disassembly preserves those instructions and retains
|
||||
the same source byte limit and explicit truncation reporting.
|
||||
|
||||
## Interpret the result
|
||||
|
||||
- Package inspection retains decoded manifest XML, summary declarations,
|
||||
|
||||
+2
-1
@@ -59,7 +59,8 @@ alone, use `rea instructions`. A macOS `.app` bundle can be supplied directly.
|
||||
Run `rea --help` or a command's `--help` for arguments and output options.
|
||||
The [generated catalog](product-catalog.json) lists all CLI commands and MCP
|
||||
tools. Provider-specific target support is described in the
|
||||
[native guide](native-investigation.md), [DOS guide](ghidra-dos.md), and
|
||||
[native guide](native-investigation.md), [DOS guide](ghidra-dos.md),
|
||||
[raw binary guide](raw-binary.md), and
|
||||
[Windows Ghidra guide](windows-ghidra-p0.md).
|
||||
|
||||
## Choose a provider
|
||||
|
||||
@@ -323,15 +323,48 @@ substitute version-dependent Electron defaults for omitted `webPreferences`.
|
||||
Dynamic option objects, bridge keys, API objects, and IPC channel expressions
|
||||
remain unknown and make coverage partial.
|
||||
|
||||
Electron API identity follows proven lexical module aliases. Bundled CommonJS
|
||||
namespace imports are also followed through the interop helpers that bundlers
|
||||
and compilers emit (`__toESM`, `__importStar`, `_interopRequireWildcard`),
|
||||
including the `electron = __toESM(electron)` rewrap that Rolldown emits. This
|
||||
step is inferred: a helper is recognized by its emitted name and a single
|
||||
program-scope function definition, and its body is not evaluated, so a local
|
||||
function that reuses one of these names is trusted to pass the module through.
|
||||
Other reassigned bindings, dynamic selections, and visibly overwritten namespace
|
||||
members are unresolved.
|
||||
Electron API identity follows proven lexical module aliases. Namespace interop
|
||||
also preserves identity when the complete Rolldown helper operations, lexical
|
||||
roles, live getters, and captured intrinsic origins match, or when a stable
|
||||
helper simply returns its module parameter. Harmless single-statement control
|
||||
blocks preserve recognition; added operations still require proof. Literal
|
||||
member and destructuring projections are retained from proven results.
|
||||
Omitted or literal node-mode arguments preserve named exports; a module-valued
|
||||
default projection requires a truthy literal node mode. Computed or extra
|
||||
arguments remain unresolved.
|
||||
Recognition uses structure rather than emitted names; other helper bodies and ambiguous
|
||||
runtime fallbacks remain unresolved. Captured function identities survive later global-property
|
||||
replacement, including copies through initialized aliases. Reads before an
|
||||
alias initializer remain unresolved. Visible intrinsic writes before capture or
|
||||
conversion are checked in their owning callable scope, including identifier leaves in nested/default/rest
|
||||
destructuring and loop targets. Property keys and shadowed local bindings do not
|
||||
overwrite the global intrinsic identity. Cross-call side effects, including
|
||||
writes inside directly invoked local functions, are not evaluated. Other
|
||||
reassignments, dynamic selections, and visibly overwritten namespace members
|
||||
are unresolved.
|
||||
Known Object/Reflect mutators remain recognizable through literal destructuring
|
||||
of intrinsic objects and stable bound-function aliases. Calls retain bound
|
||||
argument prefixes and the original bound receiver through `call`, `apply`, and
|
||||
`Reflect.apply`, including generic `Function.prototype` invocation and binding
|
||||
creation. Arguments follow each actual callable invocation rather than property
|
||||
chain depth; rebinding retains the original bound receiver.
|
||||
Visibly replaced invocation intrinsics produce unknown effects instead
|
||||
of using their former call semantics; captured function aliases retain their
|
||||
earlier identity. Invocation member reads are checked separately from the earlier
|
||||
function capture. Comma-expression callees use their final value while all
|
||||
preceding expressions remain in the effect traversal. Call effects are
|
||||
classified after callee and argument effects have been collected. Unexamined
|
||||
targets remain unresolved. `Reflect.set` examines its explicit receiver as well
|
||||
as its target, retaining unknown receiver effects. Creating an unused binding
|
||||
does not itself mutate an intrinsic. Variable redeclarations retain a single
|
||||
unconditional initializer
|
||||
when they introduce no assignment or second initializer.
|
||||
Stable identifier chains to fresh object, array, function,
|
||||
undecorated class or RegExp syntax keep those targets separate from intrinsic
|
||||
objects when initialized before use; opaque, decorated, reassigned or
|
||||
not-yet-initialized targets remain unresolved. Writes during class initialization
|
||||
are still retained. Function declarations are available before their textual
|
||||
position; variable and class initializers must precede use.
|
||||
Direct and destructuring assignment, loop, update, and delete targets are checked
|
||||
through namespace aliases; unrelated member writes do not discard observed API
|
||||
identity. This static check does
|
||||
@@ -425,9 +458,29 @@ such as `./web3:app.js` still names a local artifact.
|
||||
Package `exports` fallback arrays are supported both at the top level and under
|
||||
the root `"."` entry. The resolver selects targets in declared order using the
|
||||
same conditional and invalid-entry handling as nested exports arrays.
|
||||
Nonempty arrays containing only inactive conditions remain unmatched, allowing
|
||||
the enclosing condition object to continue to a later active condition.
|
||||
Empty arrays and explicit null targets keep their blocking outcome.
|
||||
Refusal evidence distinguishes those source values and retains condition names
|
||||
from unmatched nested targets rather than reporting array indices.
|
||||
For imports and requires, the active Node conditions include `module-sync`;
|
||||
earlier active conditions retain precedence over later ones.
|
||||
|
||||
Exact package-private `#alias` specifiers resolve against the importer's
|
||||
enclosing `package.json` `imports` map — the nearest same-container package
|
||||
scope, stopping at a `node_modules` directory so a nested package cannot inherit
|
||||
an ancestor's aliases. Selected targets are package-local `./` files with no
|
||||
extension or index fallback, using the same condition, array, and null selection
|
||||
as exports subpaths. A missing key, explicit null, or out-of-scope alias keeps
|
||||
an unresolved edge with that reason. Wildcard keys (`#internal/*`), recursive
|
||||
`#` targets, and external-package import targets remain unresolved.
|
||||
|
||||
Exact keys such as `#/x` are literal lookup identities. `#` and names ending
|
||||
in `/` are invalid. Imports arrays skip invalid parent-relative, absolute, and
|
||||
URL targets before selecting a later package-local file; an unsupported bare
|
||||
package or recursive alias keeps its unresolved outcome rather than selecting
|
||||
a later fallback.
|
||||
|
||||
ESM relative module paths and selected package exports targets use URL suffix handling
|
||||
and one percent-decoding pass. CommonJS relative paths and legacy package main
|
||||
fields retain literal filename punctuation. Exports targets must start with
|
||||
|
||||
+30
-9
@@ -150,13 +150,15 @@ structured data and matching text projection. Oversized errors are retained
|
||||
as Evidence before delivery of a bounded diagnostic with an export reference;
|
||||
if retention is unavailable or fails, the diagnostic reports that reason.
|
||||
|
||||
REA accepts ordinary `tools/call` progress tokens. Updates are monotonic,
|
||||
rate-bounded to at most one intermediate update per 100 ms, and always allow a
|
||||
terminal update. Unknown totals are omitted; REA does not fabricate percentages.
|
||||
REA accepts ordinary `tools/call` progress tokens. The numeric `progress` counts
|
||||
emitted status observations and strictly increases, including when a waiting
|
||||
phase has completed no additional work. Updates are rate-bounded to at most one
|
||||
intermediate update per 100 ms and always allow a terminal update. `total` is
|
||||
omitted because the number of future status observations is unknown. Read
|
||||
`message` for the phase and observed work; REA does not fabricate percentages.
|
||||
`capture_process_scenario` uses that boundary only when the client supplies a
|
||||
progress token. Notifications set `progress` to the count of collected terminal
|
||||
frames, process samples, and interaction events, omit `total`, and put the
|
||||
lifecycle phase, elapsed time, and final cleanup status in `message`. A client
|
||||
progress token. Notifications put the lifecycle phase, elapsed time, and final
|
||||
cleanup status in `message`. A client
|
||||
that does not send a progress token receives no progress notifications. The
|
||||
tool result is unchanged either way.
|
||||
Provider calls receive the request cancellation signal. Artifact traversal,
|
||||
@@ -230,6 +232,18 @@ engine readiness or a percentage of Ghidra auto-analysis. A longer server
|
||||
startup allowance does not extend the client's deadline; progress also does not
|
||||
extend it unless the client explicitly implements that policy.
|
||||
|
||||
While Ghidra startup is pending, REA sends a waiting notification every ten
|
||||
seconds when the request has a progress token. Its message gives elapsed waiting
|
||||
time; import, auto-analysis and bridge readiness may all still be pending.
|
||||
Waiting notifications stop when startup settles or the caller cancels. They do
|
||||
not measure engine work completed.
|
||||
|
||||
The pinned SDK can reset the request's inactivity timeout on progress with
|
||||
`resetTimeoutOnProgress: true`. Also set `maxTotalTimeout` to bound the complete
|
||||
request; the provider's startup deadline still applies. These options belong in
|
||||
the same second argument of `callTool`. Without that explicit client policy, the
|
||||
default 60-second request deadline still expires despite waiting notifications.
|
||||
|
||||
The 240-second setting is a measured example, not a universal timeout: a
|
||||
controlled Linux x64/WSL2 fixture took about 64 seconds for its first overview
|
||||
with Ghidra 12.1.4 on a mounted NTFS installation, native JDK 21, two CPUs, and a
|
||||
@@ -265,9 +279,10 @@ observed process-family member remained after final close. This was a small
|
||||
1,024-byte fixture, so the longer request setting remains an example, not a
|
||||
guarantee for larger targets. No macOS cold-start recovery was exercised.
|
||||
|
||||
With a supplied progress token, the Windows run received an operation-start
|
||||
With a supplied progress token, that earlier Windows run received an operation-start
|
||||
notification before timeout and start/completion notifications for the
|
||||
successful retry. It received no intermediate import or auto-analysis progress.
|
||||
successful retry, before startup waiting notifications were added. It received
|
||||
no intermediate import or auto-analysis progress.
|
||||
These operation markers do not measure analysis work completed or extend the
|
||||
client's deadline. Each new provider session still imports the target into a
|
||||
fresh temporary project.
|
||||
@@ -435,7 +450,13 @@ Tool annotations describe effects and are hints, not authorization controls
|
||||
([MCP ToolAnnotations](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations)).
|
||||
`readOnlyHint` includes session state: an analysis call that records additive
|
||||
Evidence is marked non-read-only even when it leaves the target unchanged.
|
||||
`destructiveHint` describes possible data loss, not ordinary Evidence recording.
|
||||
`destructiveHint` is true when a tool may discard data (overwriting or clearing
|
||||
analyst metadata, replacing files, dropping session state), runs or drives code
|
||||
REA does not own (`executesForeignCode`: process, LLDB, Electron, browser, and
|
||||
native UI scenarios), or changes an attached Android device (`mutatesDevice`:
|
||||
push, install, uninstall, start, and stop). Ordinary Evidence recording is not
|
||||
destructive. The effect record in `binary_session` and the generated catalog
|
||||
carries each flag separately.
|
||||
Effect metadata covers possible behavior across supported inputs: DMG inventory
|
||||
can launch `hdiutil` and create an owned temporary mount directory; extraction
|
||||
creates a fresh output directory on every call. Comparing supplied web captures
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
# Headerless raw-binary analysis with Ghidra
|
||||
|
||||
REA admits a headerless executable when the caller supplies the CPU family and
|
||||
the address where file offset 0 should be mapped. That interpretation is not
|
||||
inferred from a `.bin` suffix or from unrecognized bytes.
|
||||
|
||||
## Open and inspect
|
||||
|
||||
```bash
|
||||
rea inspect /absolute/path/to/ecu.bin --target-format raw-binary --architecture arm --entry-point 0x8000000 --provider ghidra --json
|
||||
rea function /absolute/path/to/ecu.bin 0x8000000 --target-format raw-binary --architecture arm --entry-point 0x8000000 --provider ghidra --json
|
||||
rea inspect-native-load-image /absolute/path/to/ecu.bin --target-format raw-binary --architecture arm --entry-point 0x8000000 --provider ghidra --json
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "open_binary",
|
||||
"arguments": {
|
||||
"path": "/absolute/path/to/ecu.bin",
|
||||
"format": "raw-binary",
|
||||
"architecture": "arm",
|
||||
"entry_point": "0x8000000",
|
||||
"provider_id": "ghidra"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`architecture` is one of `x86`, `x86_64`, `arm`, or `arm64`. `entry_point` is a
|
||||
hexadecimal address of the form `0x…`. The complete file is mapped starting at
|
||||
that address, and Ghidra seeds an `entry` function there before auto-analysis.
|
||||
ARM and AArch64 entries must be 4-byte aligned; x86 entries may be byte-aligned.
|
||||
`open_binary` and an open `binary_session` return the canonical `entry_point`
|
||||
for raw targets so callers can verify the selected mapping directly.
|
||||
Omitted `format` keeps header-based detection; architecture and entry without
|
||||
`format=raw-binary` are rejected.
|
||||
|
||||
Ghidra imports a private snapshot with `BinaryLoader` and these little-endian
|
||||
generic languages:
|
||||
|
||||
| architecture | language_id |
|
||||
| ------------ | ------------------- |
|
||||
| x86 | `x86:LE:32:default` |
|
||||
| x86_64 | `x86:LE:64:default` |
|
||||
| arm | `ARM:LE:32:v7` |
|
||||
| arm64 | `AARCH64:LE:64:v8A` |
|
||||
|
||||
Those settings, the caller-supplied entry, and `language_selection:
|
||||
caller-supplied-v1` are committed in the analysis profile. A different entry
|
||||
or architecture is a different profile; snapshots from header-detected targets
|
||||
do not replay.
|
||||
|
||||
The mapped start is independent of Ghidra's program image base, which remains
|
||||
`0x0` for BinaryLoader. Ghidra may report additional language-defined entry
|
||||
points, including unmapped ARM vectors. Load-image verification requires the
|
||||
caller-supplied entry and preserves those other entries as observations.
|
||||
Independent raw verification streams the complete private snapshot digest and
|
||||
extent with bounded memory and supports cancellation during the read.
|
||||
|
||||
Hopper and IDA refuse raw-binary targets. Windows Ghidra P0 continues to admit
|
||||
PE applications only.
|
||||
|
||||
## Limitations
|
||||
|
||||
- Headers are not discovered from file bytes. This increment does not guess
|
||||
load addresses, vector tables, or memory maps.
|
||||
- Big-endian, Thumb-only, Cortex-M, and other Ghidra processor variants are
|
||||
unsupported.
|
||||
- Reset vectors, memory-mapped I/O, and firmware boot sequences are not
|
||||
emulated.
|
||||
- Independent load-image verification covers source identity, mapped file
|
||||
bytes, the bound language, and the caller-supplied entry. Original bytes
|
||||
stay unchanged.
|
||||
@@ -793,6 +793,14 @@ truncation constraint, while leading-zero coordinates still resolve correctly.
|
||||
It has the same Ghidra/JDK prerequisites as the MZ lane. Neither lane claims DOS
|
||||
runtime or PC-98 device execution.
|
||||
|
||||
`npm run verify:ghidra:raw` uses a generated ARM little-endian headerless image
|
||||
through the compiled CLI and stdio MCP server. With the same Ghidra/JDK
|
||||
prerequisites, it checks preparation and bridge startup, verified load mappings,
|
||||
instruction and byte readback, canonical-entry session reuse, replacement when
|
||||
the entry changes without `provider_id`, unchanged source bytes, and owned
|
||||
cleanup. Other raw CPU families remain covered by deterministic tests rather
|
||||
than this real-provider lane. See [raw binary analysis](raw-binary.md).
|
||||
|
||||
## Apple Interface Builder archives
|
||||
|
||||
`npm run verify:interface-builder` compiles the source-owned AppKit XIB into a
|
||||
|
||||
@@ -55,6 +55,7 @@
|
||||
"bridge/ghidra/ReaGhidraPrepareCom.java",
|
||||
"bridge/ghidra/ReaGhidraApplySeeds.java",
|
||||
"bridge/ghidra/ReaGhidraNoReturnFix.java",
|
||||
"bridge/ghidra/ReaGhidraPrepareRaw.java",
|
||||
"bridge/android/ReaJadxBridge.java",
|
||||
"bridge/mitmproxy/capture.py",
|
||||
"scripts/rea.mjs",
|
||||
@@ -166,6 +167,7 @@
|
||||
"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:raw": "npm run build:cached && node scripts/verify-real-ghidra-raw.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/apple/interface-builder.mjs",
|
||||
"verify:ghidra:cross-format": "npm run build:cached && node scripts/verify-real-ghidra.mjs --cross-format",
|
||||
|
||||
@@ -177,6 +177,7 @@ const scriptCollisions = [
|
||||
"ReaGhidraPrepareCom.java",
|
||||
"ReaGhidraApplySeeds.java",
|
||||
"ReaGhidraNoReturnFix.java",
|
||||
"ReaGhidraPrepareRaw.java",
|
||||
];
|
||||
await mkdir(callerDirectory);
|
||||
for (const name of scriptCollisions) await mkdir(join(callerDirectory, name));
|
||||
@@ -394,15 +395,15 @@ try {
|
||||
return evidence.normalized_result;
|
||||
},
|
||||
);
|
||||
const expected = (
|
||||
const { GHIDRA_MUTATING_OPERATIONS, GHIDRA_SESSION_CAPABILITIES } =
|
||||
await import(
|
||||
pathToFileURL(join(packageRoot, "dist/ghidra/GhidraSessionValues.js"))
|
||||
)
|
||||
).GHIDRA_SESSION_CAPABILITIES.filter(
|
||||
);
|
||||
const expected = GHIDRA_SESSION_CAPABILITIES.filter(
|
||||
(name) =>
|
||||
name !== "ping" &&
|
||||
name !== "shutdown" &&
|
||||
name !== "annotate_native_function",
|
||||
!GHIDRA_MUTATING_OPERATIONS.has(name),
|
||||
);
|
||||
assert.ok(
|
||||
expected.every((name) => report.mcpOperations.includes(name)),
|
||||
@@ -440,7 +441,10 @@ try {
|
||||
token,
|
||||
"Analysis changed caller token authority.",
|
||||
);
|
||||
assert.deepEqual((await readdir(callerDirectory)).sort(), scriptCollisions);
|
||||
assert.deepEqual(
|
||||
(await readdir(callerDirectory)).sort(),
|
||||
[...scriptCollisions].sort(),
|
||||
);
|
||||
for (const name of scriptCollisions)
|
||||
assert.deepEqual(await readdir(join(callerDirectory, name)), []);
|
||||
report.callerScriptCollisionsPreserved = true;
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
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 { 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 { inspectGhidraInstallation } from "../dist/ghidra/GhidraInstallation.js";
|
||||
import { requireMcpOperationResult } from "./lib/mcp-verifier-results.mjs";
|
||||
import { createVerifierRun, completeVerifierRun } from "./lib/verifier-run.mjs";
|
||||
|
||||
if (process.argv.length !== 2)
|
||||
throw new Error("Usage: node scripts/verify-real-ghidra-raw.mjs");
|
||||
if (!["linux", "darwin"].includes(process.platform))
|
||||
throw new Error(
|
||||
"Raw-binary verification requires a Linux or macOS Ghidra host.",
|
||||
);
|
||||
if (process.env.GHIDRA_INSTALL_DIR === undefined)
|
||||
throw new Error(
|
||||
"Set GHIDRA_INSTALL_DIR to a bring-your-own Ghidra installation.",
|
||||
);
|
||||
const installation = inspectGhidraInstallation({
|
||||
environment: process.env,
|
||||
installDir: process.env.GHIDRA_INSTALL_DIR,
|
||||
...(process.env.JAVA_HOME === undefined
|
||||
? {}
|
||||
: { javaHome: process.env.JAVA_HOME }),
|
||||
});
|
||||
assert.equal(installation.status, "available", JSON.stringify(installation));
|
||||
|
||||
const run = createVerifierRun();
|
||||
const workspace = await mkdtemp(join(tmpdir(), "rea-raw-proof-"));
|
||||
const runtime = join(workspace, "runtime");
|
||||
await mkdir(runtime);
|
||||
const bytes = Buffer.from("1eff2fe1", "hex"); // ARM little-endian bx lr.
|
||||
const sha256 = createHash("sha256").update(bytes).digest("hex");
|
||||
const path = join(workspace, "image.bin");
|
||||
await writeFile(path, bytes);
|
||||
const entrypoint = fileURLToPath(new URL("./rea.mjs", import.meta.url));
|
||||
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,
|
||||
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-raw-proof", version: "1" });
|
||||
let stderr = "";
|
||||
transport.stderr?.on("data", (chunk) => {
|
||||
stderr = (stderr + chunk.toString()).slice(-65536);
|
||||
});
|
||||
let report;
|
||||
try {
|
||||
await client.connect(transport);
|
||||
const profiles = [];
|
||||
const sessions = [];
|
||||
for (const entryPoint of ["0x08000000", "0x8000000", "0x09000000"]) {
|
||||
// Omit provider_id to exercise reuse of the current provider route.
|
||||
const opened = await call("open_binary", {
|
||||
path,
|
||||
format: "raw-binary",
|
||||
architecture: "arm",
|
||||
entry_point: entryPoint,
|
||||
});
|
||||
const entry = `0x${BigInt(entryPoint).toString(16)}`;
|
||||
assert.equal(opened.entry_point, entry);
|
||||
const image = await call("inspect_native_load_image");
|
||||
assert.equal(
|
||||
image.normalized_result.status,
|
||||
"verified",
|
||||
JSON.stringify(image),
|
||||
);
|
||||
assert.equal(image.normalized_result.base_address, entry);
|
||||
assert.equal(image.normalized_result.entry.address, entry);
|
||||
assert.equal(
|
||||
image.normalized_result.observations.language_id,
|
||||
"ARM:LE:32:v7",
|
||||
);
|
||||
assert.ok(
|
||||
image.normalized_result.observations.entry_points.includes(entry),
|
||||
);
|
||||
assert.equal(image.analysis_profile.parameters.entry_point, entry);
|
||||
profiles.push(image.analysis_profile.digest);
|
||||
const status = await call("binary_session");
|
||||
assert.equal(status.entry_point, entry);
|
||||
sessions.push(status.analysis_run.run_id);
|
||||
const memory = await call("read_bytes", {
|
||||
address: entry,
|
||||
length: bytes.length,
|
||||
});
|
||||
assert.equal(memory.normalized_result.bytes_hex, bytes.toString("hex"));
|
||||
const procedures = await call("list_procedures");
|
||||
assert.ok(
|
||||
procedures.normalized_result.some(
|
||||
(procedure) => procedure.address === entry,
|
||||
),
|
||||
);
|
||||
const instruction = await call("inspect_native_instruction", {
|
||||
address: entry,
|
||||
});
|
||||
assert.equal(instruction.normalized_result.address, entry);
|
||||
}
|
||||
assert.equal(profiles[0], profiles[1]);
|
||||
assert.notEqual(profiles[1], profiles[2]);
|
||||
assert.equal(sessions[0], sessions[1]);
|
||||
assert.notEqual(sessions[1], sessions[2]);
|
||||
const rejected = await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: {
|
||||
path,
|
||||
format: "raw-binary",
|
||||
architecture: "arm64",
|
||||
entry_point: "0x8000001",
|
||||
},
|
||||
});
|
||||
assert.equal(rejected.isError, true);
|
||||
assert.match(JSON.stringify(rejected.content), /must be 4-byte aligned/);
|
||||
const unchanged = await call("binary_session");
|
||||
assert.equal(unchanged.analysis_run.run_id, sessions[2]);
|
||||
assert.equal(unchanged.entry_point, "0x9000000");
|
||||
await call("close_binary");
|
||||
|
||||
const { stdout } = await promisify(execFile)(
|
||||
process.execPath,
|
||||
[
|
||||
entrypoint,
|
||||
"inspect-native-load-image",
|
||||
path,
|
||||
"--target-format",
|
||||
"raw-binary",
|
||||
"--architecture",
|
||||
"arm",
|
||||
"--entry-point",
|
||||
"0x08000000",
|
||||
"--provider",
|
||||
"ghidra",
|
||||
"--json",
|
||||
],
|
||||
{ env, timeout: 240000, maxBuffer: 16 * 1024 * 1024 },
|
||||
);
|
||||
const cli = parseEvidence(JSON.parse(stdout));
|
||||
assert.equal(cli.subject.digest.sha256, sha256);
|
||||
assert.equal(cli.normalized_result.status, "verified");
|
||||
assert.equal(cli.normalized_result.base_address, "0x8000000");
|
||||
assert.equal(cli.analysis_profile.digest, profiles[0]);
|
||||
assert.deepEqual(await readFile(path), bytes);
|
||||
report = {
|
||||
ok: true,
|
||||
mocked: false,
|
||||
lane: "ghidra-raw",
|
||||
host: process.platform,
|
||||
provider: { id: "ghidra", version: installation.providerVersion },
|
||||
target: {
|
||||
format: "raw-binary",
|
||||
architecture: "arm",
|
||||
sha256,
|
||||
bytes: bytes.length,
|
||||
},
|
||||
transport: { cli: true, stdio_mcp: true },
|
||||
canonical_entry_reuses_session: true,
|
||||
changed_entry_replaces_session: true,
|
||||
lifecycle_entry_preserved: true,
|
||||
invalid_entry_preserves_active_session: true,
|
||||
load_images_verified: true,
|
||||
original_unchanged: true,
|
||||
};
|
||||
} catch (error) {
|
||||
if (stderr.trim()) process.stderr.write(stderr);
|
||||
throw error;
|
||||
} finally {
|
||||
await client.close();
|
||||
await transport.close();
|
||||
await rm(workspace, { recursive: true, force: true });
|
||||
}
|
||||
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",
|
||||
);
|
||||
|
||||
async function call(name, args = {}) {
|
||||
const result = await client.callTool(
|
||||
{ name, arguments: args },
|
||||
{ timeout: 240000 },
|
||||
);
|
||||
assert.notEqual(result.isError, true, JSON.stringify(result));
|
||||
const projected = requireMcpOperationResult(result, name);
|
||||
if (
|
||||
name === "open_binary" ||
|
||||
name === "close_binary" ||
|
||||
name === "binary_session"
|
||||
)
|
||||
return projected;
|
||||
const evidence = parseEvidence(result.structuredContent);
|
||||
assert.equal(evidence.subject.digest.sha256, sha256);
|
||||
assert.equal(evidence.subject.format, "raw-binary");
|
||||
return evidence;
|
||||
}
|
||||
@@ -21,14 +21,17 @@ import { SUPPORTED_GHIDRA_VERSION } from "../dist/ghidra/GhidraInstallationPolic
|
||||
import { GhidraHeadlessLauncher } from "../dist/ghidra/GhidraLauncher.js";
|
||||
import { GHIDRA_PROVIDER_IDENTITY } from "../dist/ghidra/GhidraProviderCapabilities.js";
|
||||
import { windowsP0Capabilities } from "../dist/ghidra/GhidraProviderCapabilities.js";
|
||||
import { GHIDRA_SESSION_CAPABILITIES } from "../dist/ghidra/GhidraSessionValues.js";
|
||||
import {
|
||||
GHIDRA_MUTATING_OPERATIONS,
|
||||
GHIDRA_SESSION_CAPABILITIES,
|
||||
} from "../dist/ghidra/GhidraSessionValues.js";
|
||||
import { parseBinaryTarget } from "../dist/application/BinaryTargetResolver.js";
|
||||
import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs";
|
||||
import { verifyGhidraCompactReferences } from "./lib/real-ghidra-compact-references.mjs";
|
||||
|
||||
const verifierRun = createVerifierRun();
|
||||
const SESSION_CAPABILITIES = GHIDRA_SESSION_CAPABILITIES.filter(
|
||||
(name) => name !== "annotate_native_function",
|
||||
(name) => !GHIDRA_MUTATING_OPERATIONS.has(name),
|
||||
);
|
||||
|
||||
if (process.platform !== "win32" || process.arch !== "x64")
|
||||
@@ -236,10 +239,8 @@ try {
|
||||
|
||||
const expected = [
|
||||
...GHIDRA_INVENTORY_OPERATIONS,
|
||||
...GHIDRA_FUNCTION_OPERATIONS.filter(
|
||||
(name) => name !== "annotate_native_function",
|
||||
),
|
||||
];
|
||||
...GHIDRA_FUNCTION_OPERATIONS,
|
||||
].filter((name) => !GHIDRA_MUTATING_OPERATIONS.has(name));
|
||||
if (
|
||||
observed.size !== expected.length ||
|
||||
expected.some((operation) => !observed.has(operation))
|
||||
|
||||
@@ -7,13 +7,16 @@ import { promisify } from "node:util";
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { parseEvidence } from "../../../dist/domain/evidence.js";
|
||||
import { hashAndroidFile } from "../../../dist/android/AndroidTargetSnapshot.js";
|
||||
import { hashAndroidFile } from "./digest.mjs";
|
||||
import { JADX_RELEASE } from "../../../dist/android/JadxRelease.js";
|
||||
import fixture from "../../fixtures/android/apidemos.json" with { type: "json" };
|
||||
import { verifyAndroidCliCancellation } from "./cli-cancellation.mjs";
|
||||
import { verifyAndroidMetadata } from "./metadata.mjs";
|
||||
import { verifyAndroidFailureRecovery } from "./failure-recovery.mjs";
|
||||
import { resolveJadxConfiguration } from "../../../dist/android/JadxConfiguration.js";
|
||||
import {
|
||||
resolveJadxConfigurationInputs,
|
||||
validateJadxConfiguration,
|
||||
} from "../../../dist/android/JadxConfiguration.js";
|
||||
import { verifyWindowsAndroidLifecycle } from "./windows-lifecycle.mjs";
|
||||
|
||||
const repository = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
|
||||
@@ -35,10 +38,16 @@ assert.equal(
|
||||
JADX_RELEASE.sha256,
|
||||
"Real Android lane requires the audited headless JADX release JAR",
|
||||
);
|
||||
const { java, jvmArguments } = await resolveJadxConfiguration(
|
||||
const configuration = await resolveJadxConfigurationInputs(
|
||||
process.env,
|
||||
"inspect_android_package",
|
||||
);
|
||||
await validateJadxConfiguration(
|
||||
configuration,
|
||||
process.env,
|
||||
"inspect_android_package",
|
||||
);
|
||||
const { java, jvmArguments } = configuration;
|
||||
const execute = promisify(execFile);
|
||||
await execute(java, ["-version"], { timeout: 10_000 });
|
||||
const entrypoint =
|
||||
@@ -52,6 +61,8 @@ await verifyAndroidMetadata({
|
||||
repository,
|
||||
execute,
|
||||
jvmArguments,
|
||||
entrypoint,
|
||||
environment,
|
||||
bridge: resolve(dirname(entrypoint), "../bridge/android/ReaJadxBridge.java"),
|
||||
});
|
||||
const tasks = [
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { createReadStream } from "node:fs";
|
||||
|
||||
/** Verify artifact identity without depending on private runtime snapshot helpers. */
|
||||
export const hashAndroidFile = async (path) => {
|
||||
const hash = createHash("sha256");
|
||||
for await (const bytes of createReadStream(path)) hash.update(bytes);
|
||||
return hash.digest("hex");
|
||||
};
|
||||
@@ -0,0 +1,130 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { parseEvidence } from "../../../dist/domain/evidence.js";
|
||||
import { hashAndroidFile } from "./digest.mjs";
|
||||
|
||||
/** Verify folded field assignments and remaining static-block calls through both public adapters. */
|
||||
export const verifyAndroidInitializers = async ({
|
||||
apk,
|
||||
repository,
|
||||
entrypoint,
|
||||
environment,
|
||||
execute,
|
||||
}) => {
|
||||
const digest = await hashAndroidFile(apk);
|
||||
const cases = [
|
||||
{
|
||||
class_name: "fixture.InitializationPolicy",
|
||||
witnesses: [
|
||||
"declared-policy",
|
||||
"->singletonList",
|
||||
"->POLICY:Ljava/util/List;",
|
||||
],
|
||||
},
|
||||
{
|
||||
class_name: "fixture.MixedInitialization",
|
||||
witnesses: ["field-value", "->LABEL:Ljava/lang/String;", "->touch()V"],
|
||||
},
|
||||
];
|
||||
const check = (value, scenario) => {
|
||||
const evidence = parseEvidence(value);
|
||||
assert.equal(evidence.subject.digest.sha256, digest);
|
||||
const result = evidence.normalized_result;
|
||||
assert.equal(result.class_name, scenario.class_name);
|
||||
assert.equal(result.method.name, "<clinit>");
|
||||
assert.equal(result.overload_count, 1);
|
||||
assert.equal(result.body_status, "available");
|
||||
assert.equal(result.representation, "smali");
|
||||
assert.equal(result.fell_back, true);
|
||||
assert.ok(result.markers.includes("static_initializer_disassembly"));
|
||||
assert.equal(result.source.status, "complete");
|
||||
for (const witness of scenario.witnesses)
|
||||
assert.ok(
|
||||
result.source.text.includes(witness),
|
||||
`Missing initializer evidence: ${witness}`,
|
||||
);
|
||||
return evidence;
|
||||
};
|
||||
const cli = new Map();
|
||||
for (const scenario of cases) {
|
||||
const response = await execute(
|
||||
process.execPath,
|
||||
[
|
||||
entrypoint,
|
||||
"inspect-android-method",
|
||||
apk,
|
||||
scenario.class_name,
|
||||
"<clinit>",
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
{
|
||||
cwd: repository,
|
||||
env: environment,
|
||||
timeout: 150_000,
|
||||
maxBuffer: 8 * 1024 * 1024,
|
||||
},
|
||||
);
|
||||
cli.set(scenario.class_name, check(JSON.parse(response.stdout), scenario));
|
||||
}
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [entrypoint, "mcp"],
|
||||
cwd: repository,
|
||||
env: environment,
|
||||
stderr: "pipe",
|
||||
});
|
||||
let stderr = "";
|
||||
transport.stderr?.on("data", (chunk) => {
|
||||
stderr += chunk.toString();
|
||||
});
|
||||
const client = new Client({
|
||||
name: "rea-real-android-initializers",
|
||||
version: "1",
|
||||
});
|
||||
try {
|
||||
await client.connect(transport, { timeout: 30_000 });
|
||||
for (const scenario of cases) {
|
||||
const response = await client.callTool(
|
||||
{
|
||||
name: "inspect_android_method",
|
||||
arguments: {
|
||||
path: apk,
|
||||
class_name: scenario.class_name,
|
||||
method_name: "<clinit>",
|
||||
},
|
||||
},
|
||||
{ timeout: 150_000 },
|
||||
);
|
||||
assert.notEqual(response.isError, true, JSON.stringify(response));
|
||||
const evidence = check(response.structuredContent, scenario);
|
||||
assert.deepEqual(
|
||||
evidence.normalized_result,
|
||||
cli.get(scenario.class_name).normalized_result,
|
||||
);
|
||||
assert.deepEqual(
|
||||
evidence.parameters,
|
||||
cli.get(scenario.class_name).parameters,
|
||||
);
|
||||
assert.deepEqual(
|
||||
evidence.provider,
|
||||
cli.get(scenario.class_name).provider,
|
||||
);
|
||||
}
|
||||
await client.ping();
|
||||
} catch (cause) {
|
||||
process.stderr.write(stderr);
|
||||
throw cause;
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
assert.equal(
|
||||
await hashAndroidFile(apk),
|
||||
digest,
|
||||
"Static inspection changed fixture bytes",
|
||||
);
|
||||
console.log(
|
||||
"PASS real CLI/MCP static initializer evidence, identity, parity and unchanged APK",
|
||||
);
|
||||
};
|
||||
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { delimiter, join, resolve } from "node:path";
|
||||
import { verifyAndroidInitializers } from "./initializers.mjs";
|
||||
|
||||
/** Prove cold metadata stays unmaterialized and overload identities survive code generation. */
|
||||
export const verifyAndroidMetadata = async ({
|
||||
@@ -11,6 +12,8 @@ export const verifyAndroidMetadata = async ({
|
||||
bridge,
|
||||
repository,
|
||||
execute,
|
||||
entrypoint,
|
||||
environment,
|
||||
jvmArguments = [],
|
||||
}) => {
|
||||
const javac =
|
||||
@@ -55,6 +58,8 @@ export const verifyAndroidMetadata = async ({
|
||||
`${classes}${delimiter}${jar}`,
|
||||
"ReaJadxMetadataRegression",
|
||||
apk,
|
||||
resolve(repository, "tests/fixtures/android/static-initializers"),
|
||||
classes,
|
||||
],
|
||||
{ timeout: 120_000, maxBuffer: 8 * 1024 * 1024 },
|
||||
);
|
||||
@@ -62,9 +67,23 @@ export const verifyAndroidMetadata = async ({
|
||||
result.stdout,
|
||||
/METADATA_REGRESSION_PASS classes=\d+ overloads=3/u,
|
||||
);
|
||||
assert.match(
|
||||
result.stdout,
|
||||
/INITIALIZER_REGRESSION_PASS folded=2 bounded=true/u,
|
||||
);
|
||||
console.log(
|
||||
"PASS real cold metadata, full generic types and stable overloaded method selection",
|
||||
);
|
||||
console.log(
|
||||
"PASS real folded and mixed static initializers, absent bodies and bounded smali",
|
||||
);
|
||||
await verifyAndroidInitializers({
|
||||
apk: resolve(classes, "initializers.apk"),
|
||||
repository,
|
||||
entrypoint,
|
||||
environment,
|
||||
execute,
|
||||
});
|
||||
} finally {
|
||||
await rm(classes, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
@@ -13,7 +13,10 @@ import { dirname, join } from "node:path";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { resolveJadxConfiguration } from "../../../dist/android/JadxConfiguration.js";
|
||||
import {
|
||||
resolveJadxConfigurationInputs,
|
||||
validateJadxConfiguration,
|
||||
} from "../../../dist/android/JadxConfiguration.js";
|
||||
|
||||
/** Verify real Windows cancellation, disconnect and abrupt CLI owner exit. */
|
||||
export async function verifyWindowsAndroidLifecycle(options) {
|
||||
@@ -36,7 +39,12 @@ export async function verifyWindowsAndroidLifecycle(options) {
|
||||
}
|
||||
|
||||
async function verifyJavaSelection(environment) {
|
||||
const selected = await resolveJadxConfiguration(
|
||||
const selected = await resolveJadxConfigurationInputs(
|
||||
environment,
|
||||
"inspect_android_package",
|
||||
);
|
||||
await validateJadxConfiguration(
|
||||
selected,
|
||||
environment,
|
||||
"inspect_android_package",
|
||||
);
|
||||
@@ -51,7 +59,12 @@ async function verifyJavaSelection(environment) {
|
||||
// The owned junction borrows the selected JDK directory without copying it.
|
||||
await symlink(dirname(selected.java), alias, "junction");
|
||||
pathEnvironment.Path = `"${alias}"`;
|
||||
const onPath = await resolveJadxConfiguration(
|
||||
const onPath = await resolveJadxConfigurationInputs(
|
||||
pathEnvironment,
|
||||
"inspect_android_package",
|
||||
);
|
||||
await validateJadxConfiguration(
|
||||
onPath,
|
||||
pathEnvironment,
|
||||
"inspect_android_package",
|
||||
);
|
||||
|
||||
@@ -26,6 +26,8 @@ import {
|
||||
validateDosComLength,
|
||||
type ExecutableFormatHint,
|
||||
} from "../domain/dosCom.js";
|
||||
import { admitRawBinary } from "../domain/rawBinary.js";
|
||||
import type { BinaryArchitecture } from "../domain/binaryTargetTypes.js";
|
||||
import { mzWindowsHeaderOffset } from "../domain/dosMz.js";
|
||||
import {
|
||||
hasZipSignature,
|
||||
@@ -45,6 +47,8 @@ export interface BinaryTargetResolverOptions {
|
||||
readonly hostArchitecture?: NodeJS.Architecture;
|
||||
readonly targetKind?: BinaryTarget["kind"];
|
||||
readonly formatHint?: ExecutableFormatHint;
|
||||
readonly architecture?: BinaryArchitecture;
|
||||
readonly entryPoint?: string;
|
||||
readonly signal?: AbortSignal;
|
||||
}
|
||||
|
||||
@@ -61,7 +65,7 @@ export const parseBinaryTarget = async (
|
||||
> => {
|
||||
const cwd = options.cwd ?? process.cwd();
|
||||
const hostArchitecture = options.hostArchitecture ?? process.arch;
|
||||
const { targetKind, formatHint, signal } = options;
|
||||
const { targetKind, formatHint, signal, architecture, entryPoint } = options;
|
||||
const candidate = isAbsolute(input) ? input : resolve(cwd, input);
|
||||
try {
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
@@ -83,6 +87,40 @@ export const parseBinaryTarget = async (
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
const metadata = await handle.stat();
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
if (formatHint === "raw-binary") {
|
||||
if (targetKind !== undefined && targetKind !== "executable")
|
||||
return err(
|
||||
new BinaryTargetError(
|
||||
path,
|
||||
"raw-binary format requires an executable target kind",
|
||||
),
|
||||
);
|
||||
const admitted = admitRawBinary({
|
||||
architecture,
|
||||
entryPoint,
|
||||
fileBytes: metadata.size,
|
||||
});
|
||||
if (!admitted.ok)
|
||||
return err(new BinaryTargetError(path, admitted.error));
|
||||
return ok({
|
||||
path,
|
||||
sourcePath: canonical,
|
||||
sha256: await sha256Handle(handle, path, metadata, signal),
|
||||
kind: "executable",
|
||||
format: "raw-binary",
|
||||
architecture: admitted.value.architecture,
|
||||
availableArchitectures: [admitted.value.architecture],
|
||||
entryPoint: admitted.value.entryPoint,
|
||||
entryPointSource: admitted.value.entryPointSource,
|
||||
});
|
||||
}
|
||||
if (architecture !== undefined || entryPoint !== undefined)
|
||||
return err(
|
||||
new BinaryTargetError(
|
||||
path,
|
||||
"architecture and entry_point apply only with format=raw-binary",
|
||||
),
|
||||
);
|
||||
if (formatHint === "dos-com") {
|
||||
if (targetKind !== undefined && targetKind !== "executable")
|
||||
return err(
|
||||
@@ -194,7 +232,13 @@ const detectArtifactFormat = async (
|
||||
): Promise<
|
||||
| Exclude<
|
||||
BinaryTarget["format"],
|
||||
"analysis-database" | "mach-o" | "elf" | "pe" | "dos-mz" | "dos-com"
|
||||
| "analysis-database"
|
||||
| "mach-o"
|
||||
| "elf"
|
||||
| "pe"
|
||||
| "dos-mz"
|
||||
| "dos-com"
|
||||
| "raw-binary"
|
||||
>
|
||||
| undefined
|
||||
> => {
|
||||
@@ -244,7 +288,13 @@ const namedArtifactFormat = (
|
||||
const isArchiveFormat = (
|
||||
format: Exclude<
|
||||
BinaryTarget["format"],
|
||||
"analysis-database" | "mach-o" | "elf" | "pe" | "dos-mz" | "dos-com"
|
||||
| "analysis-database"
|
||||
| "mach-o"
|
||||
| "elf"
|
||||
| "pe"
|
||||
| "dos-mz"
|
||||
| "dos-com"
|
||||
| "raw-binary"
|
||||
>,
|
||||
): format is Extract<BinaryTarget, { kind: "archive" }>["format"] =>
|
||||
isZipPackageFormat(format) || ["asar", "dmg", "pkg"].includes(format);
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
clientRequirementsFor,
|
||||
NO_CLIENT_FEATURES,
|
||||
} from "./CapabilityClientRequirements.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
|
||||
const statusSchema = z.object({
|
||||
open: z.boolean(),
|
||||
@@ -210,7 +211,7 @@ export const buildCapabilityInventory = (
|
||||
reason: availability.reason,
|
||||
remediation: availability.remediation,
|
||||
};
|
||||
}).sort((left, right) => left.name.localeCompare(right.name));
|
||||
}).sort((left, right) => compareUnicodeCodePoints(left.name, right.name));
|
||||
};
|
||||
|
||||
const availabilityFor = (context: AvailabilityContext): Availability => {
|
||||
|
||||
@@ -18,6 +18,7 @@ import { z } from "zod";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import type { SetupClient } from "./SupportedClients.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
|
||||
export type ClientConfigurationFormat = NonNullable<SetupClient["format"]>;
|
||||
export type ClientServersKey = "mcp_servers" | "mcpServers" | "mcp" | "servers";
|
||||
@@ -63,7 +64,7 @@ const normalizeConfigurationValue = (value: unknown): unknown => {
|
||||
return value;
|
||||
return Object.fromEntries(
|
||||
Object.entries(value)
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.sort(([left], [right]) => compareUnicodeCodePoints(left, right))
|
||||
.map(([key, nested]) => [key, normalizeConfigurationValue(nested)]),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
type ClientConfigurationDocument,
|
||||
} from "./ClientConfigurationDocument.js";
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
|
||||
/** Read explicit REA overrides without dropping peers when one value is invalid. */
|
||||
export const clientRegistrationEnvironment = (
|
||||
@@ -47,7 +48,7 @@ export const clientRegistrationEnvironment = (
|
||||
return ok(
|
||||
Object.fromEntries(
|
||||
Object.entries(environment).sort(([left], [right]) =>
|
||||
left.localeCompare(right),
|
||||
compareUnicodeCodePoints(left, right),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
supportedClients,
|
||||
} from "./SupportedClients.js";
|
||||
import type { SetupClient } from "./SupportedClients.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
|
||||
interface ClientRegistrationStatusBase {
|
||||
readonly client: string;
|
||||
@@ -184,7 +185,7 @@ export const readClientRegistrationStatuses = async (
|
||||
}
|
||||
}
|
||||
return statuses.sort((left, right) =>
|
||||
left.client.localeCompare(right.client),
|
||||
compareUnicodeCodePoints(left.client, right.client),
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ExecutableFormatHint } from "../domain/dosCom.js";
|
||||
import type { BinaryArchitecture } from "../domain/binaryTargetTypes.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { DirectAnalysisDependencies } from "./DirectAnalysisDependencies.js";
|
||||
import type { BinarySession } from "./binary/BinarySession.js";
|
||||
@@ -91,6 +92,8 @@ export const runDirectAnalysis = async (
|
||||
readonly signal?: AbortSignal;
|
||||
readonly providerId?: AnalysisProviderSelector;
|
||||
readonly formatHint?: ExecutableFormatHint;
|
||||
readonly architecture?: BinaryArchitecture;
|
||||
readonly entryPoint?: string;
|
||||
} = {},
|
||||
): Promise<JsonValue> =>
|
||||
withProcessCancellation(options.signal, (signal) =>
|
||||
@@ -101,6 +104,12 @@ export const runDirectAnalysis = async (
|
||||
...(options.formatHint === undefined
|
||||
? {}
|
||||
: { formatHint: options.formatHint }),
|
||||
...(options.architecture === undefined
|
||||
? {}
|
||||
: { architecture: options.architecture }),
|
||||
...(options.entryPoint === undefined
|
||||
? {}
|
||||
: { entryPoint: options.entryPoint }),
|
||||
...(options.providerId === undefined
|
||||
? {}
|
||||
: { providerId: options.providerId }),
|
||||
@@ -187,6 +196,8 @@ const runAnalysis = async (
|
||||
readonly signal: AbortSignal;
|
||||
readonly providerId?: AnalysisProviderSelector;
|
||||
readonly formatHint?: ExecutableFormatHint;
|
||||
readonly architecture?: BinaryArchitecture;
|
||||
readonly entryPoint?: string;
|
||||
},
|
||||
): Promise<JsonValue> => {
|
||||
const { logger, signal, snapshotPath } = options;
|
||||
@@ -203,6 +214,12 @@ const runAnalysis = async (
|
||||
...(options.formatHint === undefined
|
||||
? {}
|
||||
: { formatHint: options.formatHint }),
|
||||
...(options.architecture === undefined
|
||||
? {}
|
||||
: { architecture: options.architecture }),
|
||||
...(options.entryPoint === undefined
|
||||
? {}
|
||||
: { entryPoint: options.entryPoint }),
|
||||
});
|
||||
if (!prepared.ok) return cliError(prepared.error);
|
||||
const { snapshot } = prepared.value;
|
||||
@@ -214,6 +231,12 @@ const runAnalysis = async (
|
||||
...(options.formatHint === undefined
|
||||
? {}
|
||||
: { formatHint: options.formatHint }),
|
||||
...(options.architecture === undefined
|
||||
? {}
|
||||
: { architecture: options.architecture }),
|
||||
...(options.entryPoint === undefined
|
||||
? {}
|
||||
: { entryPoint: options.entryPoint }),
|
||||
...(options.providerId === undefined
|
||||
? {}
|
||||
: { providerId: options.providerId }),
|
||||
@@ -246,6 +269,12 @@ const runAnalysis = async (
|
||||
...(options.formatHint === undefined
|
||||
? {}
|
||||
: { formatHint: options.formatHint }),
|
||||
...(options.architecture === undefined
|
||||
? {}
|
||||
: { architecture: options.architecture }),
|
||||
...(options.entryPoint === undefined
|
||||
? {}
|
||||
: { entryPoint: options.entryPoint }),
|
||||
...(snapshot === undefined ? {} : { snapshot }),
|
||||
...(options.providerId === undefined
|
||||
? {}
|
||||
@@ -440,6 +469,8 @@ const withProcessCancellation = async <Value>(
|
||||
const prepareSnapshot = async (options: {
|
||||
readonly path: string;
|
||||
readonly formatHint?: ExecutableFormatHint;
|
||||
readonly architecture?: BinaryArchitecture;
|
||||
readonly entryPoint?: string;
|
||||
readonly snapshotPath: string | undefined;
|
||||
readonly signal: AbortSignal;
|
||||
}): Promise<
|
||||
@@ -458,6 +489,12 @@ const prepareSnapshot = async (options: {
|
||||
...(options.formatHint === undefined
|
||||
? {}
|
||||
: { formatHint: options.formatHint }),
|
||||
...(options.architecture === undefined
|
||||
? {}
|
||||
: { architecture: options.architecture }),
|
||||
...(options.entryPoint === undefined
|
||||
? {}
|
||||
: { entryPoint: options.entryPoint }),
|
||||
});
|
||||
if (!target.ok) return target;
|
||||
if (!snapshotMatchesTarget(loaded.value.target, target.value))
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
semanticObligationPolicy,
|
||||
type ReconstructionObligationCandidatePolicy,
|
||||
} from "./ReconstructionObligationPolicies.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
|
||||
type CandidateFields = Omit<
|
||||
ReconstructionObligation,
|
||||
@@ -54,7 +55,7 @@ export const deriveReconstructionObligationCandidates = (
|
||||
addCandidate(candidates, reviewedCandidate(obligation, records));
|
||||
return {
|
||||
candidates: [...candidates.values()].sort((left, right) =>
|
||||
left.obligation_id.localeCompare(right.obligation_id),
|
||||
compareUnicodeCodePoints(left.obligation_id, right.obligation_id),
|
||||
),
|
||||
limitations: [...limitations].sort(),
|
||||
};
|
||||
@@ -430,7 +431,7 @@ const uniqueBy = <Value>(
|
||||
key: (value: Value) => string,
|
||||
): Value[] =>
|
||||
[...new Map(values.map((value) => [key(value), value])).values()].sort(
|
||||
(left, right) => key(left).localeCompare(key(right)),
|
||||
(left, right) => compareUnicodeCodePoints(key(left), key(right)),
|
||||
);
|
||||
|
||||
const obligationId = (key: string): string =>
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
ReconstructionObligationManifest,
|
||||
} from "../domain/reconstructionObligationLedgerSchemas.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
|
||||
type Diagnostic = ReconstructionObligation["diagnostics"][number];
|
||||
type Binding = NonNullable<ReconstructionObligation["binding"]>;
|
||||
@@ -50,7 +51,8 @@ export const uniqueObligationDiagnostics = (
|
||||
]),
|
||||
).values(),
|
||||
].sort((left, right) =>
|
||||
`${left.code}:${left.detail}`.localeCompare(
|
||||
compareUnicodeCodePoints(
|
||||
`${left.code}:${left.detail}`,
|
||||
`${right.code}:${right.detail}`,
|
||||
),
|
||||
);
|
||||
|
||||
@@ -36,6 +36,7 @@ import {
|
||||
obligationReports,
|
||||
summarizeObligations,
|
||||
} from "./ReconstructionObligationLedgerProjection.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
|
||||
type Diagnostic = ReconstructionObligation["diagnostics"][number];
|
||||
type Binding = NonNullable<ReconstructionObligation["binding"]>;
|
||||
@@ -60,7 +61,7 @@ export const evaluateReconstructionObligationLedger = ({
|
||||
}): ReconstructionObligationLedger => {
|
||||
const bundle = parseEvidenceBundle(bundleInput);
|
||||
const allCandidates = [...candidatesInput].sort((left, right) =>
|
||||
left.obligation_id.localeCompare(right.obligation_id),
|
||||
compareUnicodeCodePoints(left.obligation_id, right.obligation_id),
|
||||
);
|
||||
const orphanManifestIds = findOrphanManifestIds(allCandidates, manifest);
|
||||
const candidates = allCandidates;
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { Evidence } from "../domain/evidence.js";
|
||||
import type { ReconstructionObligation } from "../domain/reconstructionObligationLedgerSchemas.js";
|
||||
import { evidenceSupportsOriginalAuthority } from "./ReconstructionObligationAuthority.js";
|
||||
import type { ReconstructionObligationCandidate } from "./ReconstructionObligationCandidates.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
|
||||
type Binding = NonNullable<ReconstructionObligation["binding"]>;
|
||||
type Diagnostic = ReconstructionObligation["diagnostics"][number];
|
||||
@@ -21,7 +22,8 @@ export const originalCasesFor = (
|
||||
),
|
||||
).values(),
|
||||
].sort((left, right) =>
|
||||
`${left.kind}:${left.evidence_id}:${left.location}`.localeCompare(
|
||||
compareUnicodeCodePoints(
|
||||
`${left.kind}:${left.evidence_id}:${left.location}`,
|
||||
`${right.kind}:${right.evidence_id}:${right.location}`,
|
||||
),
|
||||
);
|
||||
|
||||
@@ -15,6 +15,7 @@ import type {
|
||||
} from "./SetupTypes.js";
|
||||
import type { SetupClient } from "./SupportedClients.js";
|
||||
import type { DoctorReport } from "./Doctor.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
|
||||
/** Read-only setup facts shared by client selection and preflight. */
|
||||
export interface SetupDiscovery {
|
||||
@@ -308,7 +309,7 @@ const clientConfigurationDetail = (
|
||||
installHopper: boolean,
|
||||
): string => {
|
||||
const entries = Object.entries(environment)
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.sort(([left], [right]) => compareUnicodeCodePoints(left, right))
|
||||
.map(([name, value]) => `${name}=${value}`);
|
||||
const environmentDetail =
|
||||
entries.length === 0
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { DoctorProviderInspection } from "./Doctor.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
|
||||
/** Preserve adapter-published settings independently of runtime readiness. */
|
||||
export const providerRegistrationEnvironment = (
|
||||
@@ -9,5 +10,5 @@ export const providerRegistrationEnvironment = (
|
||||
.flatMap(({ registrationEnvironment }) =>
|
||||
Object.entries(registrationEnvironment),
|
||||
)
|
||||
.sort(([left], [right]) => left.localeCompare(right)),
|
||||
.sort(([left], [right]) => compareUnicodeCodePoints(left, right)),
|
||||
);
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
HermesClientPathError,
|
||||
resolveHermesClientHome,
|
||||
} from "./HermesClientHome.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
|
||||
/** One supported client configuration location. */
|
||||
export interface SetupClient {
|
||||
@@ -642,6 +643,6 @@ export const clientSkillDirectories = (
|
||||
});
|
||||
}
|
||||
return [...destinations.values()].sort((left, right) =>
|
||||
left.directory.localeCompare(right.directory),
|
||||
compareUnicodeCodePoints(left.directory, right.directory),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import type { EvidenceWriter } from "../investigation/InvestigationRecordPort.js";
|
||||
import { createEvidence, type Evidence } from "../../domain/evidence.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import { ok, type Result } from "../../domain/result.js";
|
||||
|
||||
/**
|
||||
* Complete class-inventory pages dominate raw-call provenance for focused
|
||||
* searches: one traversal embeds every examined class name regardless of the
|
||||
* match count. The summary keeps the pagination audit inline (totals, page
|
||||
* offsets and sizes, elided item counts) and links the retained record that
|
||||
* still carries the complete inventory.
|
||||
*/
|
||||
const elideInventoryText = (text: string): string | undefined => {
|
||||
let page: JsonValue;
|
||||
try {
|
||||
page = JSON.parse(text) as JsonValue;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
if (
|
||||
typeof page !== "object" ||
|
||||
page === null ||
|
||||
Array.isArray(page) ||
|
||||
!Array.isArray(page.items)
|
||||
)
|
||||
return undefined;
|
||||
const { items, ...audited } = page;
|
||||
return JSON.stringify({ ...audited, items_omitted: items.length });
|
||||
};
|
||||
|
||||
/** Replace inventoried page bodies with their pagination audit. */
|
||||
const summarizeInventoryCall = (call: JsonValue): JsonValue => {
|
||||
if (
|
||||
typeof call !== "object" ||
|
||||
call === null ||
|
||||
Array.isArray(call) ||
|
||||
call.operation !== "list_classes"
|
||||
)
|
||||
return call;
|
||||
const response = call.response;
|
||||
if (
|
||||
typeof response !== "object" ||
|
||||
response === null ||
|
||||
Array.isArray(response) ||
|
||||
!Array.isArray(response.content)
|
||||
)
|
||||
return call;
|
||||
let elided = false;
|
||||
const content = response.content.map((entry: JsonValue) => {
|
||||
if (
|
||||
typeof entry !== "object" ||
|
||||
entry === null ||
|
||||
Array.isArray(entry) ||
|
||||
typeof entry.text !== "string"
|
||||
)
|
||||
return entry;
|
||||
const summarized = elideInventoryText(entry.text);
|
||||
if (summarized === undefined) return entry;
|
||||
elided = true;
|
||||
return { ...entry, text: summarized };
|
||||
});
|
||||
return elided
|
||||
? { ...call, inventory_elided: true, response: { ...response, content } }
|
||||
: call;
|
||||
};
|
||||
|
||||
/**
|
||||
* Retain the complete search Evidence — full raw provider calls included —
|
||||
* in the session record, then deliver a bounded summary Evidence inline.
|
||||
* Callers without a retaining session keep the complete inline delivery, so
|
||||
* complete CLI JSON output is unchanged. Coverage metadata stays truthful in
|
||||
* both copies: the examined inventory is never rewritten to matched-only.
|
||||
*/
|
||||
export const summarizeRetainedAndroidSearch = (
|
||||
evidence: Evidence,
|
||||
recordEvidence: EvidenceWriter["recordEvidence"] | undefined,
|
||||
): Result<Evidence, AnalysisError> => {
|
||||
if (recordEvidence === undefined) return ok(evidence);
|
||||
const recorded = recordEvidence(evidence);
|
||||
if (!recorded.ok) return recorded;
|
||||
const subject = evidence.subject;
|
||||
const raw = evidence.raw_result;
|
||||
const summarized: JsonValue =
|
||||
raw === null ||
|
||||
typeof raw !== "object" ||
|
||||
Array.isArray(raw) ||
|
||||
!Array.isArray(raw.calls)
|
||||
? raw
|
||||
: {
|
||||
...raw,
|
||||
complete_evidence_id: evidence.evidence_id,
|
||||
calls: raw.calls.map(summarizeInventoryCall),
|
||||
};
|
||||
return ok(
|
||||
createEvidence(
|
||||
subject === null
|
||||
? undefined
|
||||
: {
|
||||
path: subject.local_path,
|
||||
sha256: subject.digest.sha256,
|
||||
format: subject.format,
|
||||
...(subject.architecture === null
|
||||
? {}
|
||||
: { architecture: subject.architecture }),
|
||||
},
|
||||
evidence.provider,
|
||||
{
|
||||
operation: evidence.operation,
|
||||
parameters: evidence.parameters,
|
||||
result: evidence.normalized_result,
|
||||
rawResult: summarized,
|
||||
confidence: evidence.confidence,
|
||||
limitations: evidence.limitations,
|
||||
locations: evidence.locations,
|
||||
evidenceLinks: [evidence.evidence_id],
|
||||
},
|
||||
),
|
||||
);
|
||||
};
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
evaluateAnalysisProviderCandidate,
|
||||
type AnalysisProviderCandidateEvaluation,
|
||||
} from "./AnalysisProviderEvaluation.js";
|
||||
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
|
||||
|
||||
/** Deterministic discovery truth for one configured deep provider. */
|
||||
export interface AnalysisProviderCandidateStatus {
|
||||
@@ -109,12 +110,14 @@ export class AnalysisProviderRegistry {
|
||||
}
|
||||
this.#providers = Object.freeze(
|
||||
[...providers].sort((left, right) =>
|
||||
left.identity().id.localeCompare(right.identity().id),
|
||||
compareUnicodeCodePoints(left.identity().id, right.identity().id),
|
||||
),
|
||||
);
|
||||
this.#byId = byId;
|
||||
this.#declaredOperations = Object.freeze(
|
||||
[...declaredOperations].sort((left, right) => left.localeCompare(right)),
|
||||
[...declaredOperations].sort((left, right) =>
|
||||
compareUnicodeCodePoints(left, right),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ExecutableFormatHint } from "../../domain/dosCom.js";
|
||||
import type { BinaryArchitecture } from "../../domain/binaryTargetTypes.js";
|
||||
import type { AnalysisProviderSelector } from "../../contracts/providerSelection.js";
|
||||
import type { AnalysisProfileCommitment } from "../../domain/analysisProfile.js";
|
||||
import {
|
||||
@@ -22,6 +23,8 @@ export interface BinarySessionOpenOptions {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly targetKind?: BinaryTarget["kind"];
|
||||
readonly formatHint?: ExecutableFormatHint;
|
||||
readonly architecture?: BinaryArchitecture;
|
||||
readonly entryPoint?: string;
|
||||
readonly snapshot?: AnalysisSnapshot;
|
||||
readonly providerId?: AnalysisProviderSelector;
|
||||
}
|
||||
@@ -72,6 +75,12 @@ export const resolveSessionOpen = async (
|
||||
...(options.formatHint === undefined
|
||||
? {}
|
||||
: { formatHint: options.formatHint }),
|
||||
...(options.architecture === undefined
|
||||
? {}
|
||||
: { architecture: options.architecture }),
|
||||
...(options.entryPoint === undefined
|
||||
? {}
|
||||
: { entryPoint: options.entryPoint }),
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
});
|
||||
if (!parsed.ok) return parsed;
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import type { InvestigationRecordPort } from "../investigation/InvestigationRecordPort.js";
|
||||
import type { ExecutableFormatHint } from "../../domain/dosCom.js";
|
||||
import type { BinaryTarget } from "../../domain/binaryTargetTypes.js";
|
||||
import type {
|
||||
BinaryArchitecture,
|
||||
BinaryTarget,
|
||||
} from "../../domain/binaryTargetTypes.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import type { AnalysisSnapshot } from "../../domain/analysisSnapshot.js";
|
||||
import type { AnalysisProfileCommitment } from "../../domain/analysisProfile.js";
|
||||
@@ -44,6 +47,8 @@ export interface BinarySessionPort
|
||||
readonly signal?: AbortSignal;
|
||||
readonly targetKind?: BinaryTarget["kind"];
|
||||
readonly formatHint?: ExecutableFormatHint;
|
||||
readonly architecture?: BinaryArchitecture;
|
||||
readonly entryPoint?: string;
|
||||
readonly snapshot?: AnalysisSnapshot;
|
||||
readonly providerId?: AnalysisProviderSelector;
|
||||
},
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { BinaryTarget } from "../../domain/binaryTargetTypes.js";
|
||||
import { binaryTargetSummary } from "./BinaryTargetSummary.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import type { ProviderOperationHealth } from "../../domain/providerOperationHealth.js";
|
||||
import type {
|
||||
@@ -10,6 +11,7 @@ import type {
|
||||
SessionProviderRoute,
|
||||
SessionProviderRouter,
|
||||
} from "./SessionProviderRouter.js";
|
||||
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
|
||||
|
||||
interface BinarySessionStatusInput {
|
||||
readonly target: BinaryTarget | undefined;
|
||||
@@ -38,7 +40,9 @@ export const binarySessionStatus = ({
|
||||
}: BinarySessionStatusInput): JsonValue => {
|
||||
const capabilities = [...route.capabilities.values()]
|
||||
.filter(({ operation }) => operation !== "inventory_artifact")
|
||||
.sort((left, right) => left.operation.localeCompare(right.operation))
|
||||
.sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.operation, right.operation),
|
||||
)
|
||||
.map((descriptor) => {
|
||||
const unavailable = runtimeUnavailability.get(descriptor.operation);
|
||||
return unavailable === undefined
|
||||
@@ -68,7 +72,9 @@ export const binarySessionStatus = ({
|
||||
capabilities: candidate.capabilities
|
||||
.slice()
|
||||
.filter(({ operation }) => operation !== "inventory_artifact")
|
||||
.sort((left, right) => left.operation.localeCompare(right.operation))
|
||||
.sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.operation, right.operation),
|
||||
)
|
||||
.map(capabilityStatus),
|
||||
}));
|
||||
const common = {
|
||||
@@ -92,11 +98,7 @@ export const binarySessionStatus = ({
|
||||
: {
|
||||
open: true,
|
||||
...common,
|
||||
path: target.path,
|
||||
sha256: target.sha256,
|
||||
format: target.format,
|
||||
kind: target.kind,
|
||||
architecture: target.architecture ?? null,
|
||||
...binaryTargetSummary(target),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -105,7 +107,9 @@ const requestActivityStatus = (
|
||||
) => {
|
||||
const providers = snapshots
|
||||
.slice()
|
||||
.sort((left, right) => left.provider.id.localeCompare(right.provider.id))
|
||||
.sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.provider.id, right.provider.id),
|
||||
)
|
||||
.map(({ provider, active, queuedRequests }) => ({
|
||||
provider: providerSummary(provider),
|
||||
active:
|
||||
@@ -153,7 +157,7 @@ const processLineageStatus = (
|
||||
snapshots: snapshots
|
||||
.slice()
|
||||
.sort((left, right) =>
|
||||
left.provider.id.localeCompare(right.provider.id),
|
||||
compareUnicodeCodePoints(left.provider.id, right.provider.id),
|
||||
)
|
||||
.map(({ provider, observation }) => ({
|
||||
provider: providerSummary(provider),
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { BinaryTarget } from "../../domain/binaryTargetTypes.js";
|
||||
|
||||
/** Preserve the admitted target interpretation in public lifecycle results. */
|
||||
export const binaryTargetSummary = (target: BinaryTarget) => ({
|
||||
path: target.path,
|
||||
format: target.format,
|
||||
kind: target.kind,
|
||||
sha256: target.sha256,
|
||||
architecture: target.architecture ?? null,
|
||||
...(target.format === "raw-binary" ? { entry_point: target.entryPoint } : {}),
|
||||
});
|
||||
@@ -10,6 +10,7 @@ import type {
|
||||
ProviderIdentity,
|
||||
} from "../AnalysisProvider.js";
|
||||
import { closeAnalysisClient } from "./AnalysisClientCleanup.js";
|
||||
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
|
||||
|
||||
/** Synthetic identity for a deterministic provider set. */
|
||||
const compositeProviderIdentity = (
|
||||
@@ -53,8 +54,8 @@ export class CompositeProvider implements AnalysisProvider {
|
||||
this.#capabilities = Object.freeze(
|
||||
capabilities.sort(
|
||||
(left, right) =>
|
||||
left.operation.localeCompare(right.operation) ||
|
||||
left.provider.id.localeCompare(right.provider.id),
|
||||
compareUnicodeCodePoints(left.operation, right.operation) ||
|
||||
compareUnicodeCodePoints(left.provider.id, right.provider.id),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -122,13 +123,13 @@ export class CompositeProvider implements AnalysisProvider {
|
||||
[...clients.values()]
|
||||
.flatMap((client) => client.runtimeLineageSnapshots?.() ?? [])
|
||||
.sort((left, right) =>
|
||||
left.provider.id.localeCompare(right.provider.id),
|
||||
compareUnicodeCodePoints(left.provider.id, right.provider.id),
|
||||
),
|
||||
requestActivitySnapshots: () =>
|
||||
[...clients.values()]
|
||||
.flatMap((client) => client.requestActivitySnapshots?.() ?? [])
|
||||
.sort((left, right) =>
|
||||
left.provider.id.localeCompare(right.provider.id),
|
||||
compareUnicodeCodePoints(left.provider.id, right.provider.id),
|
||||
),
|
||||
operationHealthSnapshot: () => {
|
||||
for (const client of clients.values()) {
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
type UpdateUnknownInput,
|
||||
} from "../../domain/residualUnknown.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
|
||||
|
||||
type EvidenceLedgerFailure = EvidenceIntegrityError;
|
||||
type RecordResult = Result<"added" | "duplicate", EvidenceLedgerFailure>;
|
||||
@@ -321,7 +322,9 @@ export class EvidenceLedger {
|
||||
unknown.severity === filters.severity) &&
|
||||
(filters.domain === undefined || unknown.domain === filters.domain),
|
||||
)
|
||||
.sort((left, right) => left.unknown_id.localeCompare(right.unknown_id))
|
||||
.sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.unknown_id, right.unknown_id),
|
||||
)
|
||||
.map((unknown) => structuredClone(unknown));
|
||||
}
|
||||
|
||||
|
||||
@@ -868,6 +868,365 @@ describe("package exports exact targets", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("package import alias resolution", () => {
|
||||
it.each(["import", "require"] as const)(
|
||||
"resolves an exact #%s alias from the enclosing package imports map",
|
||||
(moduleKind) => {
|
||||
const files = aliasFiles({
|
||||
"package.json": JSON.stringify({
|
||||
imports: { "#config": "./config.cjs" },
|
||||
}),
|
||||
"main.js": "",
|
||||
"config.cjs": "",
|
||||
});
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath: "#config",
|
||||
sourcePath: "main.js",
|
||||
context: "module-specifier",
|
||||
moduleKind,
|
||||
files,
|
||||
}),
|
||||
).toMatchObject({
|
||||
resolution_status: "resolved",
|
||||
resolved_path: "config.cjs",
|
||||
declared_path: "#config",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("resolves an alias from a nested file through the enclosing package root", () => {
|
||||
const files = aliasFiles({
|
||||
"package.json": JSON.stringify({
|
||||
imports: { "#config": "./config.cjs" },
|
||||
}),
|
||||
"src/main.js": "",
|
||||
"config.cjs": "",
|
||||
});
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath: "#config",
|
||||
sourcePath: "src/main.js",
|
||||
context: "module-specifier",
|
||||
moduleKind: "require",
|
||||
files,
|
||||
}),
|
||||
).toMatchObject({
|
||||
resolution_status: "resolved",
|
||||
resolved_path: "config.cjs",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses a nested package imports map rather than the application root", () => {
|
||||
const files = aliasFiles({
|
||||
"package.json": JSON.stringify({
|
||||
imports: { "#config": "./root.cjs" },
|
||||
}),
|
||||
"root.cjs": "",
|
||||
"node_modules/fixture/package.json": JSON.stringify({
|
||||
imports: { "#config": "./local.cjs" },
|
||||
}),
|
||||
"node_modules/fixture/index.js": "",
|
||||
"node_modules/fixture/local.cjs": "",
|
||||
});
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath: "#config",
|
||||
sourcePath: "node_modules/fixture/index.js",
|
||||
context: "module-specifier",
|
||||
moduleKind: "require",
|
||||
files,
|
||||
}),
|
||||
).toMatchObject({
|
||||
resolution_status: "resolved",
|
||||
resolved_path: "node_modules/fixture/local.cjs",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not inherit an ancestor imports map across a nested package.json", () => {
|
||||
const files = aliasFiles({
|
||||
"package.json": JSON.stringify({
|
||||
imports: { "#config": "./root.cjs" },
|
||||
}),
|
||||
"root.cjs": "",
|
||||
"node_modules/fixture/package.json": "{}",
|
||||
"node_modules/fixture/index.js": "",
|
||||
});
|
||||
const outcome = resolve({
|
||||
declaredPath: "#config",
|
||||
sourcePath: "node_modules/fixture/index.js",
|
||||
context: "module-specifier",
|
||||
moduleKind: "require",
|
||||
files,
|
||||
});
|
||||
expect(outcome).toMatchObject({
|
||||
resolution_status: "external",
|
||||
resolved_path: null,
|
||||
});
|
||||
expect(outcome.limitations.join(" ")).toContain(
|
||||
"node_modules/fixture/package.json",
|
||||
);
|
||||
expect(outcome.limitations.join(" ")).not.toContain("root.cjs");
|
||||
});
|
||||
|
||||
it("does not apply a nested package map to the application root importer", () => {
|
||||
const files = aliasFiles({
|
||||
"package.json": JSON.stringify({
|
||||
imports: { "#config": "./root.cjs" },
|
||||
}),
|
||||
"main.js": "",
|
||||
"root.cjs": "",
|
||||
"node_modules/fixture/package.json": JSON.stringify({
|
||||
imports: { "#config": "./local.cjs" },
|
||||
}),
|
||||
"node_modules/fixture/local.cjs": "",
|
||||
});
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath: "#config",
|
||||
sourcePath: "main.js",
|
||||
context: "module-specifier",
|
||||
moduleKind: "require",
|
||||
files,
|
||||
}),
|
||||
).toMatchObject({
|
||||
resolution_status: "resolved",
|
||||
resolved_path: "root.cjs",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("package import alias target selection", () => {
|
||||
it("selects import and require conditions from an imports target", () => {
|
||||
const files = aliasFiles({
|
||||
"package.json": JSON.stringify({
|
||||
imports: {
|
||||
"#config": {
|
||||
import: "./config.mjs",
|
||||
require: "./config.cjs",
|
||||
default: "./fallback.js",
|
||||
},
|
||||
},
|
||||
}),
|
||||
"main.js": "",
|
||||
"config.mjs": "",
|
||||
"config.cjs": "",
|
||||
"fallback.js": "",
|
||||
});
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath: "#config",
|
||||
sourcePath: "main.js",
|
||||
context: "module-specifier",
|
||||
moduleKind: "import",
|
||||
files,
|
||||
}).resolved_path,
|
||||
).toBe("config.mjs");
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath: "#config",
|
||||
sourcePath: "main.js",
|
||||
context: "module-specifier",
|
||||
moduleKind: "require",
|
||||
files,
|
||||
}).resolved_path,
|
||||
).toBe("config.cjs");
|
||||
});
|
||||
|
||||
it("resolves array import targets at their first string entry", () => {
|
||||
const files = aliasFiles({
|
||||
"package.json": JSON.stringify({
|
||||
imports: { "#config": [{ import: "./missing.mjs" }, "./config.cjs"] },
|
||||
}),
|
||||
"main.js": "",
|
||||
"config.cjs": "",
|
||||
});
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath: "#config",
|
||||
sourcePath: "main.js",
|
||||
context: "module-specifier",
|
||||
moduleKind: "require",
|
||||
files,
|
||||
}),
|
||||
).toMatchObject({
|
||||
resolution_status: "resolved",
|
||||
resolved_path: "config.cjs",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not add an extension or index to a selected import target", () => {
|
||||
const files = aliasFiles({
|
||||
"package.json": JSON.stringify({
|
||||
imports: { "#config": "./config" },
|
||||
}),
|
||||
"main.js": "",
|
||||
"config.cjs": "",
|
||||
"config/index.js": "",
|
||||
});
|
||||
const outcome = resolve({
|
||||
declaredPath: "#config",
|
||||
sourcePath: "main.js",
|
||||
context: "module-specifier",
|
||||
moduleKind: "require",
|
||||
files,
|
||||
});
|
||||
expect(outcome).toMatchObject({
|
||||
resolution_status: "not-found",
|
||||
resolved_path: null,
|
||||
});
|
||||
expect(outcome.limitations.join(" ")).toContain(
|
||||
"import targets are exact files",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("package import alias refusals", () => {
|
||||
it("reports a missing exact alias without looking in another package", () => {
|
||||
const files = aliasFiles({
|
||||
"package.json": JSON.stringify({
|
||||
imports: { "#config": "./config.cjs" },
|
||||
}),
|
||||
"main.js": "",
|
||||
"config.cjs": "",
|
||||
});
|
||||
const outcome = resolve({
|
||||
declaredPath: "#other",
|
||||
sourcePath: "main.js",
|
||||
context: "module-specifier",
|
||||
moduleKind: "require",
|
||||
files,
|
||||
});
|
||||
expect(outcome).toMatchObject({
|
||||
resolution_status: "external",
|
||||
resolved_path: null,
|
||||
});
|
||||
expect(outcome.limitations.join(" ")).toContain("#other");
|
||||
expect(outcome.limitations.join(" ")).toContain("#config");
|
||||
});
|
||||
|
||||
it("reports an explicit null import target as blocked", () => {
|
||||
const files = aliasFiles({
|
||||
"package.json": JSON.stringify({
|
||||
imports: { "#config": null },
|
||||
}),
|
||||
"main.js": "",
|
||||
"config.cjs": "",
|
||||
});
|
||||
const outcome = resolve({
|
||||
declaredPath: "#config",
|
||||
sourcePath: "main.js",
|
||||
context: "module-specifier",
|
||||
moduleKind: "require",
|
||||
files,
|
||||
});
|
||||
expect(outcome).toMatchObject({
|
||||
resolution_status: "external",
|
||||
resolved_path: null,
|
||||
});
|
||||
expect(outcome.limitations.join(" ")).toContain("explicit null");
|
||||
});
|
||||
|
||||
it("leaves wildcard import aliases unresolved", () => {
|
||||
const files = aliasFiles({
|
||||
"package.json": JSON.stringify({
|
||||
imports: { "#internal/*": "./src/*.js" },
|
||||
}),
|
||||
"main.js": "",
|
||||
"src/util.js": "",
|
||||
});
|
||||
const outcome = resolve({
|
||||
declaredPath: "#internal/util",
|
||||
sourcePath: "main.js",
|
||||
context: "module-specifier",
|
||||
moduleKind: "import",
|
||||
files,
|
||||
});
|
||||
expect(outcome).toMatchObject({
|
||||
resolution_status: "external",
|
||||
resolved_path: null,
|
||||
});
|
||||
expect(outcome.limitations.join(" ")).toMatch(/wildcard/i);
|
||||
});
|
||||
|
||||
it("leaves recursive and external-package import targets unresolved", () => {
|
||||
const files = aliasFiles({
|
||||
"package.json": JSON.stringify({
|
||||
imports: { "#loop": "#config", "#dep": "fixture" },
|
||||
}),
|
||||
"main.js": "",
|
||||
"node_modules/fixture/index.js": "",
|
||||
});
|
||||
const recursive = resolve({
|
||||
declaredPath: "#loop",
|
||||
sourcePath: "main.js",
|
||||
context: "module-specifier",
|
||||
moduleKind: "require",
|
||||
files,
|
||||
});
|
||||
const external = resolve({
|
||||
declaredPath: "#dep",
|
||||
sourcePath: "main.js",
|
||||
context: "module-specifier",
|
||||
moduleKind: "require",
|
||||
files,
|
||||
});
|
||||
expect(recursive).toMatchObject({
|
||||
resolution_status: "external",
|
||||
resolved_path: null,
|
||||
});
|
||||
expect(recursive.limitations.join(" ")).toMatch(/recursive/i);
|
||||
expect(external).toMatchObject({
|
||||
resolution_status: "external",
|
||||
resolved_path: null,
|
||||
});
|
||||
expect(external.limitations.join(" ")).toMatch(/external-package/i);
|
||||
});
|
||||
|
||||
it("rejects reserved hash specifiers", () => {
|
||||
const files = aliasFiles({
|
||||
"package.json": JSON.stringify({
|
||||
imports: { "#config": "./config.cjs" },
|
||||
}),
|
||||
"main.js": "",
|
||||
"config.cjs": "",
|
||||
});
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath: "#",
|
||||
sourcePath: "main.js",
|
||||
context: "module-specifier",
|
||||
moduleKind: "import",
|
||||
files,
|
||||
}),
|
||||
).toMatchObject({ resolution_status: "rejected", resolved_path: null });
|
||||
});
|
||||
|
||||
it("does not use a foreign-container enclosing package.json", () => {
|
||||
const files = fileMap([
|
||||
file(
|
||||
"package.json",
|
||||
"other",
|
||||
JSON.stringify({ imports: { "#config": "./config.cjs" } }),
|
||||
),
|
||||
file("main.js", "root"),
|
||||
file("config.cjs", "root"),
|
||||
]);
|
||||
const outcome = resolve({
|
||||
declaredPath: "#config",
|
||||
sourcePath: "main.js",
|
||||
context: "module-specifier",
|
||||
moduleKind: "require",
|
||||
files,
|
||||
});
|
||||
expect(outcome).toMatchObject({
|
||||
resolution_status: "external",
|
||||
resolved_path: null,
|
||||
});
|
||||
expect(outcome.limitations.join(" ")).toContain("package scopes");
|
||||
});
|
||||
});
|
||||
|
||||
describe("directory package entrypoint precedence", () => {
|
||||
it.each([
|
||||
["require", '{"main":"actual.cjs"}', "actual.cjs"],
|
||||
@@ -1211,6 +1570,15 @@ const file = (
|
||||
: { included: true, value: text },
|
||||
});
|
||||
|
||||
const aliasFiles = (
|
||||
entries: Readonly<Record<string, string | null>>,
|
||||
): ReturnType<typeof fileMap> =>
|
||||
fileMap(
|
||||
Object.entries(entries).map(([path, text]) =>
|
||||
file(path, "root", text ?? ""),
|
||||
),
|
||||
);
|
||||
|
||||
describe("exact HTML resource resolution", () => {
|
||||
it.each([
|
||||
["extension", ["app.js"]],
|
||||
|
||||
@@ -14,6 +14,11 @@ import {
|
||||
percentDecodeUrlPath,
|
||||
stripQueryAndFragment,
|
||||
} from "../../domain/artifactPathSyntax.js";
|
||||
import {
|
||||
classifyPackageImportSpecifier,
|
||||
classifyPackageImportTargetString,
|
||||
lookupExactPackageImport,
|
||||
} from "../../domain/javascript/javascriptPackageImportAliases.js";
|
||||
|
||||
type ArtifactPathResolutionContext =
|
||||
| "package-entrypoint"
|
||||
@@ -103,6 +108,13 @@ export const resolveArtifactPathByContext = (
|
||||
};
|
||||
|
||||
const resolvePath = (input: ResolveArtifactPathInput): CandidateResolution => {
|
||||
// Package import keys are literal lookup identities, not artifact paths.
|
||||
// The selected target is admitted separately by resolveExportTarget.
|
||||
if (
|
||||
input.context === "module-specifier" &&
|
||||
input.declaredPath.startsWith("#")
|
||||
)
|
||||
return resolvePackageImportAlias(input, input.declaredPath);
|
||||
const rejected = rejectDeclaration(input.declaredPath);
|
||||
if (rejected !== null) return rejected;
|
||||
const candidate = contextualCandidate(input);
|
||||
@@ -202,9 +214,9 @@ const bareModuleCandidate = (
|
||||
declared: string,
|
||||
): CandidateResolution => {
|
||||
const packageName = barePackageName(declared);
|
||||
if (packageName === null || isBuiltin(declared) || declared.startsWith("#"))
|
||||
if (packageName === null || isBuiltin(declared))
|
||||
return unresolvedCandidate("external", [
|
||||
"The bare specifier is a Node builtin, package import map, or invalid package name.",
|
||||
"The bare specifier is a Node builtin or invalid package name.",
|
||||
]);
|
||||
if (input.moduleKind === "import" && packageName.includes("%"))
|
||||
return unresolvedCandidate("rejected", [
|
||||
@@ -235,6 +247,115 @@ const bareModuleCandidate = (
|
||||
]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Nearest same-container package.json, stopping at a `node_modules` directory
|
||||
* so a nested package cannot inherit an ancestor's map.
|
||||
*/
|
||||
const enclosingPackageMetadata = (
|
||||
input: ResolveArtifactPathInput,
|
||||
):
|
||||
| Extract<PackageMetadata, { readonly kind: "available" | "unavailable" }>
|
||||
| { readonly kind: "none" } => {
|
||||
let directory = posix.dirname(input.sourcePath);
|
||||
while (posix.basename(directory) !== "node_modules") {
|
||||
const metadata = readPackageMetadata(input, directory);
|
||||
if (metadata.kind !== "absent") return metadata;
|
||||
if (directory === "." || directory === "") break;
|
||||
directory = posix.dirname(directory);
|
||||
}
|
||||
return { kind: "none" };
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolve an exact `#alias` against the importer's enclosing `imports` map.
|
||||
* Selected relative targets are exact files; patterns, recursive aliases, and
|
||||
* external-package targets stay unresolved without falling through.
|
||||
*/
|
||||
const resolvePackageImportAlias = (
|
||||
input: ResolveArtifactPathInput,
|
||||
specifier: string,
|
||||
): CandidateResolution => {
|
||||
const classified = classifyPackageImportSpecifier(specifier);
|
||||
if (classified.kind === "invalid")
|
||||
return unresolvedCandidate("rejected", [
|
||||
`The package import specifier ${JSON.stringify(specifier)} is invalid; "#" and specifiers that end with "/" are not valid import aliases.`,
|
||||
]);
|
||||
if (classified.kind === "pattern")
|
||||
return unresolvedCandidate("external", [
|
||||
`Wildcard and directory package import aliases remain unresolved; ${JSON.stringify(specifier)} is not an exact imports key.`,
|
||||
]);
|
||||
const metadata = enclosingPackageMetadata(input);
|
||||
if (metadata.kind === "none")
|
||||
return unresolvedCandidate("external", [
|
||||
`No enclosing package.json defines package import alias ${specifier}; package import maps do not cross package scopes.`,
|
||||
]);
|
||||
if (metadata.kind === "unavailable")
|
||||
return unresolvedCandidate("unavailable", [metadata.limitation]);
|
||||
const lookup = lookupExactPackageImport(metadata.imports, specifier);
|
||||
if (lookup.kind === "undefined-map")
|
||||
return unresolvedCandidate("external", [
|
||||
`Package metadata ${metadata.path} does not define package import alias ${specifier}.`,
|
||||
]);
|
||||
if (lookup.kind === "missing-key")
|
||||
return unresolvedCandidate("external", [
|
||||
`Package metadata ${metadata.path} does not define package import alias ${specifier}; it declares ${lookup.declared.join(", ") || "no imports keys"}.`,
|
||||
]);
|
||||
if (lookup.kind === "pattern-unresolved")
|
||||
return unresolvedCandidate("external", [
|
||||
`Wildcard package import aliases remain unresolved; package metadata ${metadata.path} has no exact imports key ${specifier}.`,
|
||||
]);
|
||||
const selected = selectPackageImportTarget(lookup.target, input.moduleKind);
|
||||
if (selected.status === "rejected")
|
||||
return unresolvedCandidate("rejected", [
|
||||
`Package metadata ${metadata.path}: ${selected.limitation}`,
|
||||
]);
|
||||
if (selected.status === "unmatched")
|
||||
return unresolvedCandidate("external", [
|
||||
`Package metadata ${metadata.path} declares no imports target for alias ${specifier} under the active conditions; it declares ${selected.declared.join(", ") || "no conditions"}.`,
|
||||
]);
|
||||
if (selected.status === "blocked")
|
||||
return unresolvedCandidate("external", [
|
||||
`Package metadata ${metadata.path} blocks import alias ${specifier} with ${selected.cause === "null" ? "an explicit null imports target" : "an empty imports target array"}.`,
|
||||
]);
|
||||
if (selected.status === "non-relative") {
|
||||
const target = classifyPackageImportTargetString(selected.value);
|
||||
return unresolvedCandidate("external", [
|
||||
target.kind === "recursive"
|
||||
? `Recursive package import aliases remain unresolved; package metadata ${metadata.path} maps ${specifier} to ${JSON.stringify(target.target)}.`
|
||||
: `External-package import targets remain unresolved; package metadata ${metadata.path} maps ${specifier} to ${JSON.stringify(target.target)}.`,
|
||||
]);
|
||||
}
|
||||
return resolveExportTarget(input, metadata.path, selected.value, "imports");
|
||||
};
|
||||
|
||||
const selectPackageImportTarget = (
|
||||
value: unknown,
|
||||
moduleKind: ResolveArtifactPathInput["moduleKind"],
|
||||
):
|
||||
| { readonly status: "value"; readonly value: string }
|
||||
| { readonly status: "non-relative"; readonly value: string }
|
||||
| { readonly status: "blocked"; readonly cause: PackageTargetBlockCause }
|
||||
| { readonly status: "unmatched"; readonly declared: readonly string[] }
|
||||
| { readonly status: "rejected"; readonly limitation: string } => {
|
||||
const selected = selectExportTarget(
|
||||
value,
|
||||
packageExportConditions(moduleKind),
|
||||
"imports",
|
||||
);
|
||||
if (selected.kind === "invalid" || selected.kind === "invalid-config")
|
||||
return { status: "rejected", limitation: selected.limitation };
|
||||
if (selected.kind === "unmatched")
|
||||
return {
|
||||
status: "unmatched",
|
||||
declared: selected.declared,
|
||||
};
|
||||
if (selected.kind === "blocked")
|
||||
return { status: "blocked", cause: selected.cause };
|
||||
if (selected.kind === "non-relative")
|
||||
return { status: "non-relative", value: selected.value };
|
||||
return { status: "value", value: selected.value };
|
||||
};
|
||||
|
||||
/** Self references use the nearest package scope before dependency lookup. */
|
||||
const commonJsSelfCandidate = (
|
||||
input: ResolveArtifactPathInput,
|
||||
@@ -242,35 +363,22 @@ const commonJsSelfCandidate = (
|
||||
): CandidateResolution | null => {
|
||||
if (input.moduleKind !== "require" || !input.files.has(input.sourcePath))
|
||||
return null;
|
||||
let directory = posix.dirname(input.sourcePath);
|
||||
while (posix.basename(directory) !== "node_modules") {
|
||||
const metadata = readPackageMetadata(input, directory);
|
||||
if (metadata.kind === "unavailable")
|
||||
return unresolvedCandidate("unavailable", [metadata.limitation]);
|
||||
if (metadata.kind === "available") {
|
||||
if (
|
||||
metadata.name === undefined ||
|
||||
metadata.exports === undefined ||
|
||||
(declared !== metadata.name &&
|
||||
!declared.startsWith(`${metadata.name}/`))
|
||||
)
|
||||
return null;
|
||||
const subpath =
|
||||
declared === metadata.name
|
||||
? "."
|
||||
: `.${declared.slice(metadata.name.length)}`;
|
||||
// Self resolution does not apply the CommonJS dependency-name matcher.
|
||||
return resolvePackageExports(
|
||||
input,
|
||||
metadata.path,
|
||||
subpath,
|
||||
metadata.exports,
|
||||
);
|
||||
}
|
||||
if (directory === "." || directory === "") break;
|
||||
directory = posix.dirname(directory);
|
||||
}
|
||||
return null;
|
||||
const metadata = enclosingPackageMetadata(input);
|
||||
if (metadata.kind === "none") return null;
|
||||
if (metadata.kind === "unavailable")
|
||||
return unresolvedCandidate("unavailable", [metadata.limitation]);
|
||||
if (
|
||||
metadata.name === undefined ||
|
||||
metadata.exports === undefined ||
|
||||
(declared !== metadata.name && !declared.startsWith(`${metadata.name}/`))
|
||||
)
|
||||
return null;
|
||||
const subpath =
|
||||
declared === metadata.name
|
||||
? "."
|
||||
: `.${declared.slice(metadata.name.length)}`;
|
||||
// Self resolution does not apply the CommonJS dependency-name matcher.
|
||||
return resolvePackageExports(input, metadata.path, subpath, metadata.exports);
|
||||
};
|
||||
|
||||
/** Package roots and exact subpaths share metadata and exports selection. */
|
||||
@@ -324,16 +432,17 @@ const resolvePackageExports = (
|
||||
]);
|
||||
if (exported.status === "blocked")
|
||||
return unresolvedCandidate("external", [
|
||||
`Directory package metadata ${packagePath} blocks subpath ${subpath} with an explicit null exports target.`,
|
||||
`Directory package metadata ${packagePath} blocks subpath ${subpath} with ${exported.cause === "null" ? "an explicit null exports target" : "an empty exports target array"}.`,
|
||||
]);
|
||||
return resolveExportTarget(input, packagePath, exported.value);
|
||||
};
|
||||
|
||||
/** An exports target is a URL naming one exact file for both Node loaders. */
|
||||
/** An exports or import target is a URL naming one exact file for both Node loaders. */
|
||||
const resolveExportTarget = (
|
||||
input: ResolveArtifactPathInput,
|
||||
packagePath: string,
|
||||
target: string,
|
||||
mapKind: "exports" | "imports" = "exports",
|
||||
): CandidateResolution => {
|
||||
const rejected = rejectDeclaration(target);
|
||||
if (rejected !== null) return rejected;
|
||||
@@ -343,7 +452,7 @@ const resolveExportTarget = (
|
||||
if (typeof candidate !== "string") return candidate;
|
||||
return (
|
||||
resolveFileCandidates(input, [candidate]) ??
|
||||
exactExportsTargetNotFound(candidate)
|
||||
exactPackageTargetNotFound(candidate, mapKind)
|
||||
);
|
||||
};
|
||||
|
||||
@@ -492,6 +601,7 @@ type PackageMetadata =
|
||||
readonly path: string;
|
||||
readonly name: string | undefined;
|
||||
readonly exports: string | object | undefined;
|
||||
readonly imports: object | undefined;
|
||||
readonly main: unknown;
|
||||
readonly module: unknown;
|
||||
}
|
||||
@@ -532,6 +642,7 @@ const readPackageMetadata = (
|
||||
};
|
||||
const name = Reflect.get(value, "name");
|
||||
const exports = Reflect.get(value, "exports");
|
||||
const imports = Reflect.get(value, "imports");
|
||||
return {
|
||||
kind: "available",
|
||||
path,
|
||||
@@ -543,6 +654,11 @@ const readPackageMetadata = (
|
||||
(typeof exports === "object" && exports !== null)
|
||||
? exports
|
||||
: undefined,
|
||||
// Import maps must be non-array objects; other shapes are not a map.
|
||||
imports:
|
||||
typeof imports === "object" && imports !== null && !Array.isArray(imports)
|
||||
? imports
|
||||
: undefined,
|
||||
main: Reflect.get(value, "main"),
|
||||
module: Reflect.get(value, "module"),
|
||||
};
|
||||
@@ -644,10 +760,12 @@ const fileCandidates = (candidate: string): readonly string[] => [
|
||||
const indexCandidates = (candidate: string): readonly string[] =>
|
||||
EXTENSIONS.map((extension) => posix.join(candidate, `index${extension}`));
|
||||
|
||||
type PackageTargetBlockCause = "null" | "empty-array";
|
||||
|
||||
type PackageExportOutcome =
|
||||
| { readonly status: "value"; readonly value: string }
|
||||
| { readonly status: "rejected"; readonly limitation: string }
|
||||
| { readonly status: "blocked" }
|
||||
| { readonly status: "blocked"; readonly cause: PackageTargetBlockCause }
|
||||
| { readonly status: "unmatched"; readonly declared: readonly string[] };
|
||||
|
||||
/** Only exact non-directory keys participate; wildcard expansion is unsupported. */
|
||||
@@ -687,29 +805,33 @@ const selectPackageExport = (
|
||||
if (selected.kind === "unmatched")
|
||||
return {
|
||||
status: "unmatched",
|
||||
declared:
|
||||
typeof target === "object" && target !== null
|
||||
? Object.keys(target)
|
||||
: declared,
|
||||
declared: selected.declared,
|
||||
};
|
||||
return selected.kind === "blocked"
|
||||
? { status: "blocked" }
|
||||
: { status: "value", value: selected.value };
|
||||
if (selected.kind === "blocked")
|
||||
return { status: "blocked", cause: selected.cause };
|
||||
if (selected.kind === "non-relative")
|
||||
return {
|
||||
status: "rejected",
|
||||
limitation: `The package exports target ${JSON.stringify(selected.value)} must start with "./".`,
|
||||
};
|
||||
return { status: "value", value: selected.value };
|
||||
};
|
||||
|
||||
type ExportTargetOutcome =
|
||||
| { readonly kind: "value"; readonly value: string }
|
||||
| { readonly kind: "blocked" }
|
||||
| { readonly kind: "unmatched" }
|
||||
| { readonly kind: "non-relative"; readonly value: string }
|
||||
| { readonly kind: "blocked"; readonly cause: PackageTargetBlockCause }
|
||||
| { readonly kind: "unmatched"; readonly declared: readonly string[] }
|
||||
| { readonly kind: "invalid"; readonly limitation: string }
|
||||
| { readonly kind: "invalid-config"; readonly limitation: string };
|
||||
|
||||
const invalidExportTarget = (
|
||||
value: unknown,
|
||||
reason: string,
|
||||
mapKind: "exports" | "imports" = "exports",
|
||||
): ExportTargetOutcome => ({
|
||||
kind: "invalid",
|
||||
limitation: `The package exports target ${JSON.stringify(value) ?? String(value)} ${reason}.`,
|
||||
limitation: `The package ${mapKind === "imports" ? "import" : "exports"} target ${JSON.stringify(value) ?? String(value)} ${reason}.`,
|
||||
});
|
||||
|
||||
// Node checks raw target segments before URL normalization. Compare encoded
|
||||
@@ -729,50 +851,80 @@ const forbiddenExportSegment = (value: string): string | undefined =>
|
||||
);
|
||||
});
|
||||
|
||||
const selectStringPackageTarget = (
|
||||
value: string,
|
||||
mapKind: "exports" | "imports",
|
||||
): ExportTargetOutcome => {
|
||||
if (mapKind === "imports") {
|
||||
const target = classifyPackageImportTargetString(value);
|
||||
if (target.kind === "invalid")
|
||||
return invalidExportTarget(
|
||||
value,
|
||||
"cannot be parent-relative, absolute, or a URL",
|
||||
mapKind,
|
||||
);
|
||||
if (target.kind !== "relative") return { kind: "non-relative", value };
|
||||
} else if (!value.startsWith("./"))
|
||||
return invalidExportTarget(value, 'must start with "./"', mapKind);
|
||||
const forbidden = forbiddenExportSegment(value);
|
||||
return forbidden === undefined
|
||||
? { kind: "value", value }
|
||||
: invalidExportTarget(
|
||||
value,
|
||||
`contains forbidden path segment ${JSON.stringify(forbidden)} before URL normalization`,
|
||||
mapKind,
|
||||
);
|
||||
};
|
||||
|
||||
const selectArrayPackageTarget = (
|
||||
value: readonly unknown[],
|
||||
conditions: ReadonlySet<string>,
|
||||
mapKind: "exports" | "imports",
|
||||
): ExportTargetOutcome => {
|
||||
if (value.length === 0) return { kind: "blocked", cause: "empty-array" };
|
||||
let lastRefusal:
|
||||
| Extract<ExportTargetOutcome, { readonly kind: "invalid" | "blocked" }>
|
||||
| undefined;
|
||||
const declared = new Set<string>();
|
||||
for (const entry of value) {
|
||||
const nested = selectExportTarget(entry, conditions, mapKind);
|
||||
// Node's array fallback catches invalid targets, not invalid configuration.
|
||||
if (nested.kind === "invalid-config") return nested;
|
||||
if (nested.kind === "unmatched") {
|
||||
for (const condition of nested.declared) declared.add(condition);
|
||||
continue;
|
||||
}
|
||||
if (nested.kind === "invalid" || nested.kind === "blocked") {
|
||||
lastRefusal = nested;
|
||||
continue;
|
||||
}
|
||||
return nested;
|
||||
}
|
||||
return lastRefusal ?? { kind: "unmatched", declared: [...declared] };
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolve a target in Node's declared order. Explicit null blocks an active
|
||||
* condition, whereas an unmatched nested object permits the next condition.
|
||||
* An array skips unmatched and invalid entries, stops at its first string, and
|
||||
* preserves the final invalid-versus-null refusal if no string is selected.
|
||||
* preserves the last invalid/null outcome if no string is selected. A nonempty
|
||||
* array of unmatched conditions stays unmatched; an empty array blocks.
|
||||
*/
|
||||
const selectExportTarget = (
|
||||
value: unknown,
|
||||
conditions: ReadonlySet<string>,
|
||||
mapKind: "exports" | "imports" = "exports",
|
||||
): ExportTargetOutcome => {
|
||||
if (typeof value === "string") {
|
||||
if (!value.startsWith("./"))
|
||||
return invalidExportTarget(value, 'must start with "./"');
|
||||
const forbidden = forbiddenExportSegment(value);
|
||||
return forbidden === undefined
|
||||
? { kind: "value", value }
|
||||
: invalidExportTarget(
|
||||
value,
|
||||
`contains forbidden path segment ${JSON.stringify(forbidden)} before URL normalization`,
|
||||
);
|
||||
}
|
||||
if (value === null) return { kind: "blocked" };
|
||||
if (Array.isArray(value)) {
|
||||
let invalid: string | null = null;
|
||||
for (const entry of value) {
|
||||
const nested = selectExportTarget(entry, conditions);
|
||||
// Node's array fallback catches invalid targets, not invalid configuration.
|
||||
if (nested.kind === "invalid-config") return nested;
|
||||
if (nested.kind === "invalid") {
|
||||
invalid = nested.limitation;
|
||||
continue;
|
||||
}
|
||||
if (nested.kind === "unmatched") continue;
|
||||
invalid = null;
|
||||
if (nested.kind === "value") return nested;
|
||||
}
|
||||
return invalid === null
|
||||
? { kind: "blocked" }
|
||||
: { kind: "invalid", limitation: invalid };
|
||||
}
|
||||
if (typeof value === "string")
|
||||
return selectStringPackageTarget(value, mapKind);
|
||||
if (value === null) return { kind: "blocked", cause: "null" };
|
||||
if (Array.isArray(value))
|
||||
return selectArrayPackageTarget(value, conditions, mapKind);
|
||||
if (typeof value !== "object")
|
||||
return invalidExportTarget(
|
||||
value,
|
||||
"must be a relative string, object, array, or null",
|
||||
mapKind,
|
||||
);
|
||||
for (const key of Object.keys(value)) {
|
||||
const numeric = Number(key);
|
||||
@@ -782,12 +934,15 @@ const selectExportTarget = (
|
||||
limitation: `The package exports configuration contains numeric condition key ${JSON.stringify(key)}.`,
|
||||
};
|
||||
}
|
||||
const declared = new Set<string>();
|
||||
for (const [condition, target] of Object.entries(value)) {
|
||||
declared.add(condition);
|
||||
if (!conditions.has(condition)) continue;
|
||||
const nested = selectExportTarget(target, conditions);
|
||||
const nested = selectExportTarget(target, conditions, mapKind);
|
||||
if (nested.kind !== "unmatched") return nested;
|
||||
for (const name of nested.declared) declared.add(name);
|
||||
}
|
||||
return { kind: "unmatched" };
|
||||
return { kind: "unmatched", declared: [...declared] };
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -816,11 +971,14 @@ const notFoundCandidate = (): CandidateResolution => ({
|
||||
],
|
||||
});
|
||||
|
||||
const exactExportsTargetNotFound = (path: string): CandidateResolution => ({
|
||||
const exactPackageTargetNotFound = (
|
||||
path: string,
|
||||
mapKind: "exports" | "imports",
|
||||
): CandidateResolution => ({
|
||||
resolvedPath: null,
|
||||
status: "not-found",
|
||||
limitations: [
|
||||
`The selected package exports target ${path} does not exist in the inventoried artifact container; exports targets are exact files, so no extension or directory index was tried.`,
|
||||
`The selected package ${mapKind === "imports" ? "import" : "exports"} target ${path} does not exist in the inventoried artifact container; ${mapKind === "imports" ? "import" : "exports"} targets are exact files, so no extension or directory index was tried.`,
|
||||
],
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { orderAsarListing } from "./AsarArtifactReader.js";
|
||||
|
||||
describe("orderAsarListing", () => {
|
||||
it("orders host-spelled listings by their portable archive path", () => {
|
||||
const posix = orderAsarListing(["/a0", "/a", "/a/b"], "/");
|
||||
const windows = orderAsarListing(["\\a0", "\\a", "\\a\\b"], "\\");
|
||||
|
||||
// "/" (0x2F) precedes "0" (0x30); "\" (0x5C) would follow it.
|
||||
expect(posix.map(({ path }) => path)).toEqual(["a", "a/b", "a0"]);
|
||||
expect(windows.map(({ path }) => path)).toEqual(["a", "a/b", "a0"]);
|
||||
expect(windows.map(({ listed }) => listed)).toEqual([
|
||||
"\\a",
|
||||
"\\a\\b",
|
||||
"\\a0",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps POSIX backslashes as literal filename characters", () => {
|
||||
expect(orderAsarListing(["/a\\b"], "/")).toEqual([
|
||||
{ listed: "/a\\b", path: "a\\b" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -32,6 +32,7 @@ import { closeAsarHandle, readValidatedAsarEntry } from "./AsarEntryStream.js";
|
||||
import { admitAsarHeader } from "./AsarHeader.js";
|
||||
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
|
||||
import { readFileHandleChunks } from "../filesystem/readFileHandleChunks.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
|
||||
/**
|
||||
* Official Electron ASAR adapter with range-streamed member reads.
|
||||
@@ -64,7 +65,7 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
) {}
|
||||
|
||||
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
|
||||
let paths: string[];
|
||||
let paths: readonly AsarListedPath[];
|
||||
try {
|
||||
await this.prepareContainer(undefined, signal);
|
||||
const snapshotPath = this.#snapshotPath();
|
||||
@@ -82,9 +83,7 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
await headerHandle.close();
|
||||
}
|
||||
abortIfNeeded(signal);
|
||||
paths = listPackage(snapshotPath, { isPack: false }).sort((left, right) =>
|
||||
left.localeCompare(right, "en"),
|
||||
);
|
||||
paths = orderAsarListing(listPackage(snapshotPath, { isPack: false }));
|
||||
const archiveMetadata = await lstat(snapshotPath);
|
||||
if (!archiveMetadata.isFile() || archiveMetadata.isSymbolicLink())
|
||||
throw new ArtifactReaderFailure(
|
||||
@@ -95,13 +94,8 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
} catch (cause: unknown) {
|
||||
throw asarFailure(this.path, "inventory", cause);
|
||||
}
|
||||
for (const listed of paths) {
|
||||
for (const { listed, path } of paths) {
|
||||
abortIfNeeded(signal);
|
||||
// @electron/asar returns paths assembled with the host path module.
|
||||
// Keep that spelling for its API calls, but expose archive paths with
|
||||
// portable separators. On POSIX, backslashes can be literal filename
|
||||
// characters and must remain untouched.
|
||||
const path = toArtifactPath(listed);
|
||||
if (path.length === 0) continue;
|
||||
const providerPath = listed.startsWith(sep)
|
||||
? listed.slice(sep.length)
|
||||
@@ -577,8 +571,30 @@ const waitForOperation = async (
|
||||
});
|
||||
};
|
||||
|
||||
const toArtifactPath = (listed: string): string => {
|
||||
const portable = sep === "\\" ? listed.replaceAll("\\", "/") : listed;
|
||||
interface AsarListedPath {
|
||||
readonly listed: string;
|
||||
readonly path: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pair each host-spelled listing with its portable archive path, ordered by
|
||||
* the portable path so Windows and POSIX hosts agree.
|
||||
*
|
||||
* @electron/asar returns paths assembled with the host path module. Keep that
|
||||
* spelling for its API calls, but expose archive paths with portable
|
||||
* separators. On POSIX, backslashes can be literal filename characters and
|
||||
* must remain untouched.
|
||||
*/
|
||||
export const orderAsarListing = (
|
||||
listed: readonly string[],
|
||||
separator: string = sep,
|
||||
): AsarListedPath[] =>
|
||||
listed
|
||||
.map((entry) => ({ listed: entry, path: toArtifactPath(entry, separator) }))
|
||||
.sort((left, right) => compareUnicodeCodePoints(left.path, right.path));
|
||||
|
||||
const toArtifactPath = (listed: string, separator: string): string => {
|
||||
const portable = separator === "\\" ? listed.replaceAll("\\", "/") : listed;
|
||||
return portable.replace(/^\/+|\/+$/gu, "");
|
||||
};
|
||||
|
||||
|
||||
@@ -13,6 +13,16 @@ describe("hostExecutableMarking", () => {
|
||||
expect(
|
||||
hostExecutableMarking("C:\\scratch\\SETUP.CMD", file(0o444), "win32"),
|
||||
).toBe(true);
|
||||
for (const path of [
|
||||
"tools/SETUP.EXE",
|
||||
"run.Cmd",
|
||||
"build.bat",
|
||||
"legacy.com",
|
||||
])
|
||||
expect(hostExecutableMarking(path, file(0o666), "win32")).toBe(true);
|
||||
expect(hostExecutableMarking("readonly.exe", file(0o444), "win32")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
hostExecutableMarking("C:\\scratch\\library.dll", file(0o666), "win32"),
|
||||
).toBe(false);
|
||||
@@ -25,6 +35,11 @@ describe("hostExecutableMarking", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("does not treat other Windows filenames as executable even with execute bits", () => {
|
||||
for (const path of ["notes.txt", "README", "archive.exe.bak"])
|
||||
expect(hostExecutableMarking(path, file(0o777), "win32")).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps POSIX permission bits authoritative regardless of extension", () => {
|
||||
expect(hostExecutableMarking("/scratch/tool", file(0o755), "linux")).toBe(
|
||||
true,
|
||||
|
||||
@@ -68,6 +68,7 @@ import { captureCdpScreenshot } from "./CdpScreenshot.js";
|
||||
import { comparePngScreenshots } from "./PngVisualDiff.js";
|
||||
|
||||
import { CDP_BROWSER_PROVIDER_IDENTITY } from "./providerIdentities.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
const CLEANUP_DOMAINS = ["Network", "Debugger", "Runtime", "Page"] as const;
|
||||
|
||||
/** Passive browser observation through a selected user-owned CDP endpoint. */
|
||||
@@ -408,7 +409,9 @@ const selectTargets = (
|
||||
attached: target.attached,
|
||||
});
|
||||
}
|
||||
allowed.sort((left, right) => left.target_id.localeCompare(right.target_id));
|
||||
allowed.sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.target_id, right.target_id),
|
||||
);
|
||||
return {
|
||||
allowed,
|
||||
excluded: {
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
import { exclusionReasonForUrl } from "./CdpCaptureEventHelpers.js";
|
||||
import type { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
import { createDocumentSvgAncestry, domSvgLink } from "./CdpCaptureDomSvg.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
|
||||
export type CapturedResource = Omit<
|
||||
WebPageInspection["resources"][number],
|
||||
@@ -346,7 +347,7 @@ const accessibilityStates = (
|
||||
if (state !== undefined) states.set(name, state);
|
||||
}
|
||||
return [...states]
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.sort(([left], [right]) => compareUnicodeCodePoints(left, right))
|
||||
.map(([name, state]) => ({ name, value: state }));
|
||||
};
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
import { captureElectronScripts } from "./CdpElectronScripts.js";
|
||||
import { captureElectronWorkers } from "./CdpElectronWorkers.js";
|
||||
import { authorizedElectronFile } from "./ElectronFileScope.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
|
||||
interface ElectronContext {
|
||||
readonly connection: CdpConnection;
|
||||
@@ -300,7 +301,7 @@ const captureResources = async (
|
||||
pending.push(...recordsValue(tree.childFrames));
|
||||
}
|
||||
return resources.sort((left, right) =>
|
||||
left.resource_key.localeCompare(right.resource_key),
|
||||
compareUnicodeCodePoints(left.resource_key, right.resource_key),
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ import { inspectCdpElectronPage } from "./CdpElectronInspection.js";
|
||||
import { authorizedElectronFile } from "./ElectronFileScope.js";
|
||||
|
||||
import { CDP_ELECTRON_PROVIDER_IDENTITY } from "./providerIdentities.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
/** Passive Electron provider for local file pages exposed by loopback CDP. */
|
||||
export class CdpElectronProvider implements ElectronObservationPort {
|
||||
identity(): ProviderIdentity {
|
||||
@@ -73,7 +74,7 @@ export class CdpElectronProvider implements ElectronObservationPort {
|
||||
});
|
||||
}
|
||||
allowed.sort((left, right) =>
|
||||
left.target_id.localeCompare(right.target_id),
|
||||
compareUnicodeCodePoints(left.target_id, right.target_id),
|
||||
);
|
||||
return ok(
|
||||
electronTargetListSchema.parse({
|
||||
|
||||
@@ -9,6 +9,7 @@ import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
import { requiredScriptSource } from "./CdpCaptureValues.js";
|
||||
import type { ElectronScriptDraft } from "./CdpElectronScriptEvents.js";
|
||||
import { authorizedElectronFile } from "./ElectronFileScope.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
|
||||
interface ElectronScriptCaptureInput {
|
||||
readonly connection: CdpConnection;
|
||||
@@ -65,7 +66,7 @@ export const captureElectronScripts = async (
|
||||
return {
|
||||
total,
|
||||
items: items.sort((left, right) =>
|
||||
left.script_key.localeCompare(right.script_key),
|
||||
compareUnicodeCodePoints(left.script_key, right.script_key),
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
import type { CdpEndpointTarget } from "./CdpEndpoint.js";
|
||||
import { optionalCdpCommand } from "./CdpOptionalCommand.js";
|
||||
import { authorizedElectronFile } from "./ElectronFileScope.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
|
||||
/** Inventory local worker targets without attaching to them. */
|
||||
export const captureElectronWorkers = async (input: {
|
||||
@@ -70,7 +71,7 @@ export const captureElectronWorkers = async (input: {
|
||||
});
|
||||
}
|
||||
return workers.sort((left, right) =>
|
||||
left.target_id.localeCompare(right.target_id),
|
||||
compareUnicodeCodePoints(left.target_id, right.target_id),
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
} from "./CdpCaptureValues.js";
|
||||
import type { CaptureContext } from "./CdpPageCapture.js";
|
||||
import type { WebSourceMapRequest } from "./WebSourceMapFetcher.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
|
||||
export interface CapturedScripts {
|
||||
readonly inventory: WebPageInspection["scripts"];
|
||||
@@ -131,11 +132,15 @@ const keyAndBuildInventory = (
|
||||
}));
|
||||
keyed.sort(
|
||||
(left, right) =>
|
||||
left.base.localeCompare(right.base) ||
|
||||
sourceDigest(left.item.source).localeCompare(
|
||||
compareUnicodeCodePoints(left.base, right.base) ||
|
||||
compareUnicodeCodePoints(
|
||||
sourceDigest(left.item.source),
|
||||
sourceDigest(right.item.source),
|
||||
) ||
|
||||
(left.item.frame_id ?? "").localeCompare(right.item.frame_id ?? ""),
|
||||
compareUnicodeCodePoints(
|
||||
left.item.frame_id ?? "",
|
||||
right.item.frame_id ?? "",
|
||||
),
|
||||
);
|
||||
const totals = new Map<string, number>();
|
||||
for (const { base } of keyed) totals.set(base, (totals.get(base) ?? 0) + 1);
|
||||
|
||||
@@ -7,7 +7,10 @@ import type {
|
||||
} from "../domain/webMcpDiscovery.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { digestCanonicalValue } from "../domain/canonicalDigest.js";
|
||||
import { compositeKey } from "../domain/unicodeCodePointOrder.js";
|
||||
import {
|
||||
compareUnicodeCodePoints,
|
||||
compositeKey,
|
||||
} from "../domain/unicodeCodePointOrder.js";
|
||||
import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js";
|
||||
import type { CdpConnection, CdpEvent } from "./CdpConnection.js";
|
||||
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
@@ -521,7 +524,7 @@ const buildWebMcpResult = (options: WebMcpResultOptions): WebMcpDiscovery => {
|
||||
tools: {
|
||||
total: tools.size + completeness.droppedTotal,
|
||||
items: [...tools.values()].sort((left, right) =>
|
||||
left.tool_key.localeCompare(right.tool_key),
|
||||
compareUnicodeCodePoints(left.tool_key, right.tool_key),
|
||||
),
|
||||
},
|
||||
completeness: completeness.snapshot(),
|
||||
|
||||
@@ -6,9 +6,10 @@ import { z } from "zod";
|
||||
import { PROMPT_CONTRACTS } from "./contracts/promptContracts.js";
|
||||
import { TOOL_CONTRACTS } from "./contracts/toolContracts.js";
|
||||
import { CLI_COMMAND_NAMES } from "./cliCommandNames.js";
|
||||
import { compareUnicodeCodePoints } from "./domain/unicodeCodePointOrder.js";
|
||||
|
||||
const sortedToolContracts = [...TOOL_CONTRACTS].sort((left, right) =>
|
||||
left.name.localeCompare(right.name),
|
||||
compareUnicodeCodePoints(left.name, right.name),
|
||||
);
|
||||
|
||||
const createToolCatalog = () =>
|
||||
@@ -39,7 +40,7 @@ const promptCatalog = PROMPT_CONTRACTS.map((contract) => ({
|
||||
description: contract.description,
|
||||
arguments: contract.arguments,
|
||||
steps: contract.steps,
|
||||
})).sort((left, right) => left.name.localeCompare(right.name));
|
||||
})).sort((left, right) => compareUnicodeCodePoints(left.name, right.name));
|
||||
|
||||
const digest = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
|
||||
@@ -8,9 +8,8 @@ import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import type { Logger } from "pino";
|
||||
import {
|
||||
directAnalysisOptions,
|
||||
formatSelectionOption,
|
||||
providerSelectionOption,
|
||||
directAnalysisOptionsFromCli,
|
||||
nativeOpenOptionFields,
|
||||
} from "./options.js";
|
||||
import type { CliInstance } from "./types.js";
|
||||
import { runCliJavaScriptApplicationAnalysis } from "./javascriptApplicationAnalysis.js";
|
||||
@@ -43,8 +42,7 @@ const registerOverviewCommands = (
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
});
|
||||
cli.command(CLI_COMMANDS.analyze, {
|
||||
description: "Get an overview of an app",
|
||||
@@ -75,12 +73,7 @@ const registerOverviewCommands = (
|
||||
args.path,
|
||||
"binary_overview",
|
||||
{},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
);
|
||||
},
|
||||
@@ -97,12 +90,7 @@ const registerOverviewCommands = (
|
||||
args.path,
|
||||
"binary_overview",
|
||||
{},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -136,8 +124,7 @@ const registerDecompileCommand = (
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "decompile", () =>
|
||||
@@ -152,12 +139,7 @@ const registerDecompileCommand = (
|
||||
"procedure_pseudo_code",
|
||||
),
|
||||
},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -168,13 +150,17 @@ const routesToJavaScriptAnalysis = async (
|
||||
path: string,
|
||||
options: {
|
||||
readonly snapshot?: string | undefined;
|
||||
readonly "target-format"?: "dos-com" | undefined;
|
||||
readonly "target-format"?: "dos-com" | "raw-binary" | undefined;
|
||||
readonly architecture?: string | undefined;
|
||||
readonly "entry-point"?: string | undefined;
|
||||
readonly provider?: string | undefined;
|
||||
},
|
||||
): Promise<boolean> =>
|
||||
options.provider === undefined &&
|
||||
options.snapshot === undefined &&
|
||||
options["target-format"] === undefined &&
|
||||
options.architecture === undefined &&
|
||||
options["entry-point"] === undefined &&
|
||||
(await isJavaScriptApplicationPath(path));
|
||||
|
||||
const isJavaScriptApplicationPath = async (path: string): Promise<boolean> => {
|
||||
@@ -215,8 +201,7 @@ const registerXrefsCommand = (
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "xrefs", () =>
|
||||
@@ -231,12 +216,7 @@ const registerXrefsCommand = (
|
||||
"xrefs",
|
||||
),
|
||||
},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -270,8 +250,7 @@ const registerTraceCommand = (
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "trace", () =>
|
||||
@@ -287,12 +266,7 @@ const registerTraceCommand = (
|
||||
),
|
||||
case_sensitive: options.caseSensitive,
|
||||
},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -326,8 +300,7 @@ const registerFunctionCommand = (
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "function", () =>
|
||||
@@ -342,12 +315,7 @@ const registerFunctionCommand = (
|
||||
"analyze_function",
|
||||
),
|
||||
},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -381,8 +349,7 @@ const registerInstructionsCommand = (
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.instructions, () =>
|
||||
@@ -397,12 +364,7 @@ const registerInstructionsCommand = (
|
||||
"read_function_instructions",
|
||||
),
|
||||
},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -448,8 +410,7 @@ const registerSearchCommand = (
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "search", () =>
|
||||
@@ -468,12 +429,7 @@ const registerSearchCommand = (
|
||||
mode: options.mode,
|
||||
case_sensitive: options.caseSensitive,
|
||||
},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
@@ -5,9 +5,8 @@ import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import type { Logger } from "pino";
|
||||
import {
|
||||
directAnalysisOptions,
|
||||
formatSelectionOption,
|
||||
providerSelectionOption,
|
||||
directAnalysisOptionsFromCli,
|
||||
nativeOpenOptionFields,
|
||||
} from "./options.js";
|
||||
import type { CliInstance } from "./types.js";
|
||||
|
||||
@@ -23,8 +22,7 @@ export const registerCoreNativeCommands = (
|
||||
"Verify loaded native bytes, source mappings, relocations and entry",
|
||||
args: z.object({ path: z.string().describe("Local executable path") }),
|
||||
options: z.object({
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.inspectNativeLoadImage, () =>
|
||||
@@ -32,12 +30,7 @@ export const registerCoreNativeCommands = (
|
||||
args.path,
|
||||
"inspect_native_load_image",
|
||||
{},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -54,8 +47,7 @@ export const registerCoreNativeCommands = (
|
||||
.min(1)
|
||||
.default(256)
|
||||
.describe("Requested byte count"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.readBytes, () =>
|
||||
@@ -63,12 +55,7 @@ export const registerCoreNativeCommands = (
|
||||
args.path,
|
||||
"read_bytes",
|
||||
{ address: args.address, length: options.length },
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -79,8 +66,7 @@ export const registerCoreNativeCommands = (
|
||||
address: z.string().describe("Exact provider memory address"),
|
||||
}),
|
||||
options: z.object({
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.addressToFileOffset, () =>
|
||||
@@ -88,12 +74,7 @@ export const registerCoreNativeCommands = (
|
||||
args.path,
|
||||
"address_to_file_offset",
|
||||
{ address: args.address },
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -154,8 +135,7 @@ export const registerCoreNativeCommands = (
|
||||
.max(5000)
|
||||
.default(1000)
|
||||
.describe("Maximum nodes on this page"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.traceNativeValues, () =>
|
||||
@@ -172,12 +152,7 @@ export const registerCoreNativeCommands = (
|
||||
offset: options.offset,
|
||||
limit: options.limit,
|
||||
},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -189,8 +164,7 @@ export const registerCoreNativeCommands = (
|
||||
options: z.object({
|
||||
type: z.string().optional().describe("Exact database type category path"),
|
||||
address: z.string().optional().describe("Exact native address"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.inspectNativeDataType, () =>
|
||||
@@ -203,12 +177,7 @@ export const registerCoreNativeCommands = (
|
||||
? {}
|
||||
: { address: options.address }),
|
||||
},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -226,8 +195,7 @@ export const registerCoreNativeCommands = (
|
||||
address: z.string().describe("Exact native address"),
|
||||
}),
|
||||
options: z.object({
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, command, () =>
|
||||
@@ -235,12 +203,7 @@ export const registerCoreNativeCommands = (
|
||||
args.path,
|
||||
operation,
|
||||
{ address: args.address },
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -273,8 +236,7 @@ const registerNativeDispatchMetadataCommand = (
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load or update the local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: async ({ args, options }) =>
|
||||
logCliCommand(logger, "inspect-native-dispatch-metadata", () =>
|
||||
@@ -282,12 +244,7 @@ const registerNativeDispatchMetadataCommand = (
|
||||
args.path,
|
||||
"inspect_native_dispatch_metadata",
|
||||
{ max_records: options.maxRecords },
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -332,8 +289,7 @@ const registerNativeUiActionCommand = (
|
||||
.max(5_000)
|
||||
.default(500)
|
||||
.describe("Maximum returned graph edges"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: async ({ args, options }) =>
|
||||
logCliCommand(logger, "trace-native-ui-action", () =>
|
||||
@@ -346,12 +302,7 @@ const registerNativeUiActionCommand = (
|
||||
max_nodes: options.maxNodes,
|
||||
max_edges: options.maxEdges,
|
||||
},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -374,8 +325,7 @@ const registerNativeApiCommand = (
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "inspect-native-api", () =>
|
||||
@@ -383,12 +333,7 @@ const registerNativeApiCommand = (
|
||||
args.path,
|
||||
"inspect_native_api",
|
||||
{ procedure: args.address },
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -417,8 +362,7 @@ const registerAnnotationCommand = (
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Inline entry comment; empty text clears it"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.annotateNativeFunction, () =>
|
||||
@@ -435,12 +379,7 @@ const registerAnnotationCommand = (
|
||||
? {}
|
||||
: { inline_comment: options["inline-comment"] }),
|
||||
},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
+55
-1
@@ -2,6 +2,11 @@ import {
|
||||
executableFormatHintSchema,
|
||||
type ExecutableFormatHint,
|
||||
} from "../domain/dosCom.js";
|
||||
import type { BinaryArchitecture } from "../domain/binaryTargetTypes.js";
|
||||
import {
|
||||
binaryArchitectureSchema,
|
||||
rawBinaryEntryPointSchema,
|
||||
} from "../domain/rawBinary.js";
|
||||
import { analysisProviderSelectorSchema } from "../contracts/providerSelection.js";
|
||||
import type { AnalysisProviderSelector } from "../contracts/providerSelection.js";
|
||||
import type { Logger } from "pino";
|
||||
@@ -15,16 +20,65 @@ export const providerSelectionOption = analysisProviderSelectorSchema
|
||||
/** Explicit interpretation for headerless native executable formats. */
|
||||
export const formatSelectionOption = executableFormatHintSchema
|
||||
.optional()
|
||||
.describe("Explicit headerless DOS COM interpretation");
|
||||
.describe(
|
||||
"Explicit headerless interpretation (dos-com or raw-binary); omission preserves header-based detection",
|
||||
);
|
||||
|
||||
export const architectureSelectionOption = binaryArchitectureSchema
|
||||
.optional()
|
||||
.describe(
|
||||
"Caller-supplied CPU family; required with --target-format raw-binary",
|
||||
);
|
||||
|
||||
export const entryPointSelectionOption = rawBinaryEntryPointSchema
|
||||
.optional()
|
||||
.describe(
|
||||
"Caller-supplied load and entry address (0xhex); required with --target-format raw-binary",
|
||||
);
|
||||
|
||||
/** Shared CLI flags that bind a native target interpretation. */
|
||||
export const nativeOpenOptionFields = {
|
||||
"target-format": formatSelectionOption,
|
||||
architecture: architectureSelectionOption,
|
||||
"entry-point": entryPointSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
};
|
||||
|
||||
/** Native CLI flags consumed when opening a target for one-shot analysis. */
|
||||
export interface NativeOpenCliFlags {
|
||||
readonly snapshot?: string | undefined;
|
||||
readonly provider?: AnalysisProviderSelector | undefined;
|
||||
readonly "target-format"?: ExecutableFormatHint | undefined;
|
||||
readonly architecture?: BinaryArchitecture | undefined;
|
||||
readonly "entry-point"?: string | undefined;
|
||||
}
|
||||
|
||||
export const directAnalysisOptions = (
|
||||
logger: Logger,
|
||||
snapshotPath: string | undefined,
|
||||
providerId: AnalysisProviderSelector | undefined,
|
||||
formatHint?: ExecutableFormatHint,
|
||||
architecture?: BinaryArchitecture,
|
||||
entryPoint?: string,
|
||||
) => ({
|
||||
logger,
|
||||
snapshotPath,
|
||||
...(formatHint === undefined ? {} : { formatHint }),
|
||||
...(architecture === undefined ? {} : { architecture }),
|
||||
...(entryPoint === undefined ? {} : { entryPoint }),
|
||||
...(providerId === undefined ? {} : { providerId }),
|
||||
});
|
||||
|
||||
/** Map native CLI flags onto the shared one-shot analysis options. */
|
||||
export const directAnalysisOptionsFromCli = (
|
||||
logger: Logger,
|
||||
options: NativeOpenCliFlags,
|
||||
) =>
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
options.architecture,
|
||||
options["entry-point"],
|
||||
);
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { openBinaryInputSchema } from "./sessionLifecycleInputs.js";
|
||||
|
||||
describe("open_binary raw-binary input contract", () => {
|
||||
it("accepts header detection without architecture", () => {
|
||||
expect(
|
||||
openBinaryInputSchema.safeParse({ path: "/tmp/fixture.bin" }).success,
|
||||
).toBe(true);
|
||||
expect(
|
||||
openBinaryInputSchema.safeParse({
|
||||
path: "/tmp/legacy.com",
|
||||
format: "dos-com",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
});
|
||||
it("accepts raw-binary with architecture and entry", () => {
|
||||
expect(
|
||||
openBinaryInputSchema.safeParse({
|
||||
path: "/tmp/ecu.bin",
|
||||
format: "raw-binary",
|
||||
architecture: "arm",
|
||||
entry_point: "0x8000000",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
});
|
||||
it("rejects raw-binary without architecture or entry", () => {
|
||||
const parsed = openBinaryInputSchema.safeParse({
|
||||
path: "/tmp/ecu.bin",
|
||||
format: "raw-binary",
|
||||
});
|
||||
expect(parsed.success).toBe(false);
|
||||
expect(
|
||||
openBinaryInputSchema.safeParse({
|
||||
path: "/tmp/ecu.bin",
|
||||
format: "raw-binary",
|
||||
architecture: "arm",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
it("rejects architecture without format=raw-binary", () => {
|
||||
expect(
|
||||
openBinaryInputSchema.safeParse({
|
||||
path: "/tmp/ecu.bin",
|
||||
architecture: "arm",
|
||||
entry_point: "0x8000000",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,11 @@
|
||||
import { isAbsolute } from "node:path";
|
||||
import { executableFormatHintSchema } from "../domain/dosCom.js";
|
||||
import { localPathStringSchema } from "../domain/localPath.js";
|
||||
import {
|
||||
binaryArchitectureSchema,
|
||||
rawBinaryEntryPointSchema,
|
||||
rawBinarySelectionError,
|
||||
} from "../domain/rawBinary.js";
|
||||
import { z } from "zod";
|
||||
import { analysisProviderSelectorSchema } from "./providerSelection.js";
|
||||
|
||||
@@ -25,16 +30,51 @@ const binaryTargetPathSchema = localPathStringSchema
|
||||
);
|
||||
|
||||
/** Input contract for opening a target with an optional staged snapshot. */
|
||||
export const openBinaryInputSchema = z.strictObject({
|
||||
path: binaryTargetPathSchema,
|
||||
format: executableFormatHintSchema
|
||||
.optional()
|
||||
.describe(
|
||||
"Explicit headerless DOS COM interpretation; omission preserves header-based detection",
|
||||
),
|
||||
provider_id: analysisProviderSelectorSchema.optional(),
|
||||
snapshot_path: snapshotPathSchema.optional(),
|
||||
});
|
||||
export const openBinaryInputSchema = z
|
||||
.strictObject({
|
||||
path: binaryTargetPathSchema,
|
||||
format: executableFormatHintSchema
|
||||
.optional()
|
||||
.describe(
|
||||
"Explicit headerless interpretation: dos-com or raw-binary. Omission preserves header-based detection.",
|
||||
),
|
||||
architecture: binaryArchitectureSchema
|
||||
.optional()
|
||||
.describe(
|
||||
"Caller-supplied CPU family. Required with format=raw-binary; rejected otherwise.",
|
||||
),
|
||||
entry_point: rawBinaryEntryPointSchema
|
||||
.optional()
|
||||
.describe(
|
||||
"Caller-supplied load and entry address (0xhex). File offset 0 is mapped here. Required with format=raw-binary; rejected otherwise.",
|
||||
),
|
||||
provider_id: analysisProviderSelectorSchema.optional(),
|
||||
snapshot_path: snapshotPathSchema.optional(),
|
||||
})
|
||||
.superRefine((value, context) => {
|
||||
const pairing = rawBinarySelectionError({
|
||||
...(value.format === undefined ? {} : { format: value.format }),
|
||||
...(value.architecture === undefined
|
||||
? {}
|
||||
: { architecture: value.architecture }),
|
||||
...(value.entry_point === undefined
|
||||
? {}
|
||||
: { entryPoint: value.entry_point }),
|
||||
});
|
||||
if (pairing === undefined) return;
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path:
|
||||
value.format === "raw-binary"
|
||||
? value.architecture === undefined
|
||||
? ["architecture"]
|
||||
: ["entry_point"]
|
||||
: value.architecture === undefined
|
||||
? ["entry_point"]
|
||||
: ["architecture"],
|
||||
message: pairing,
|
||||
});
|
||||
});
|
||||
|
||||
/** Input contract for closing a target after an optional atomic snapshot. */
|
||||
export const closeBinaryInputSchema = z.strictObject({
|
||||
|
||||
@@ -69,7 +69,7 @@ export const exportEvidenceBundleInputSchema = z.strictObject({
|
||||
export const SESSION_TOOL_CONTRACTS = [
|
||||
session(
|
||||
"open_binary",
|
||||
"Open a local executable, application bundle, archive, JavaScript, source map, plist, or analysis database after validation. format=dos-com explicitly interprets 1..65280 headerless bytes as a DOS COM analysis image; omission preserves header-based detection. provider_id selects one deep provider or deterministic auto selection; the binding remains stable until close or an explicit switch, with no failure fallback. Reopening the same target and profile retains its active database and metadata edits. An optional analysis snapshot is imported atomically and must match the binary identity, concrete provider, and canonical analysis profile exactly; importing into a session with metadata mutations requires closing and reopening it first.",
|
||||
"Open a local executable, application bundle, archive, JavaScript, source map, plist, or analysis database after validation. format=dos-com explicitly interprets 1..65280 headerless bytes as a DOS COM analysis image. format=raw-binary interprets headerless bytes with a required architecture and entry_point; file offset 0 maps at that address. Omission preserves header-based detection. provider_id selects one deep provider or deterministic auto selection; the binding remains stable until close or an explicit switch, with no failure fallback. Reopening the same target and profile retains its active database and metadata edits. An optional analysis snapshot is imported atomically and must match the binary identity, concrete provider, and canonical analysis profile exactly; importing into a session with metadata mutations requires closing and reopening it first.",
|
||||
openBinaryInputSchema,
|
||||
),
|
||||
session(
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { TOOL_CONTRACTS } from "./toolContracts.js";
|
||||
import { TOOL_EFFECTS, annotationsFromEffects } from "./toolEffects.js";
|
||||
|
||||
/**
|
||||
* Descriptions that name running, launching, executing, starting, installing,
|
||||
* or uninstalling something. A matching tool must declare foreign execution or
|
||||
* device mutation unless it is listed below with the reason the wording does
|
||||
* not describe that effect.
|
||||
*/
|
||||
const EXECUTION_WORDING =
|
||||
/\b(?:run|runs|running|launch|launches|launching|execute|executes|executing|execution|start|starts|install|installs|uninstall|uninstalls)\b/iu;
|
||||
|
||||
const EXECUTION_WORDING_EXCEPTIONS: Readonly<Record<string, string>> = {
|
||||
inspect_native_load_image: "states that it does not execute the target",
|
||||
resolve_native_call_targets: "states that it does not execute code",
|
||||
inspect_pe_resources: "states that it does not execute the image",
|
||||
inspect_binary_layout:
|
||||
"parses the binary offline with operator-configured pwntools",
|
||||
inspect_recorded_crash: "inspects a core file without launching its target",
|
||||
inspect_macho: "runs host Mach-O inspection tools, not the target",
|
||||
inspect_evm_interface:
|
||||
"decodes bytecode in REA's bundled worker without executing it",
|
||||
inspect_managed_artifact: "reads metadata without executing target code",
|
||||
inspect_managed_members: "reads metadata without executing target code",
|
||||
inspect_managed_native_boundaries:
|
||||
"reads metadata without executing target code",
|
||||
verify_managed_native_boundaries: "states it does not execute managed code",
|
||||
project_managed_application_graph: "states it does not execute managed code",
|
||||
inspect_android_package: "states it does not execute the APK",
|
||||
search_android_classes: "states it does not execute the APK",
|
||||
inspect_apktool_client:
|
||||
"inspects the operator-selected apktool launcher; never installs it",
|
||||
inspect_jeb_client: "talks to a caller-started JEB; never launches it",
|
||||
open_jeb_project: "the engine analyzes the file; REA does not execute it",
|
||||
inspect_adb_client:
|
||||
"inspects the operator-selected adb client; never starts its server",
|
||||
list_adb_devices: "may start the local adb server, which REA does not own",
|
||||
inspect_firmware_regions: "states there is no target execution",
|
||||
extract_firmware: "states that extracted code is never executed",
|
||||
analyze_javascript_application: "reconstructs the graph without executing",
|
||||
reconcile_javascript_runtime: "never invents execution claims",
|
||||
observe_javascript_runtime: "never evaluates or resumes the target",
|
||||
trace_application_feature: "never executes the application",
|
||||
trace_javascript_semantics: "static reachability never claims execution",
|
||||
compare_javascript_export_shapes: "states it does not execute JavaScript",
|
||||
project_android_application_graph: "execution-free inventory",
|
||||
project_apple_application_graph: "execution-free inventory",
|
||||
trace_web_source_location: "states there is no application execution",
|
||||
trace_web_module_imports:
|
||||
"runs only REA's resolver stub in operator-configured Chromium",
|
||||
export_web_scripts: "states there is no refetch or execution",
|
||||
observe_web_execution:
|
||||
"instruments an externally driven page; it does not run code itself",
|
||||
recover_javascript_sources: "states there is no application code execution",
|
||||
goto_address: "start names an object boundary, not a launch",
|
||||
prev_address: "start names an object boundary, not a launch",
|
||||
trace_call_path: "start names the traversal origin",
|
||||
observe_native_ui: "observes an already-running app without launching it",
|
||||
inspect_adb_package: "reports install times without changing the device",
|
||||
list_adb_processes: "lists running processes without changing the device",
|
||||
inspect_web_event_listeners: "states it does not evaluate JavaScript",
|
||||
};
|
||||
|
||||
const declaresForeignAuthority = (name: string): boolean => {
|
||||
const effects = TOOL_EFFECTS[name];
|
||||
return (
|
||||
effects !== undefined &&
|
||||
(effects.executesForeignCode || effects.mutatesDevice)
|
||||
);
|
||||
};
|
||||
|
||||
describe("tool effects", () => {
|
||||
it("audits every public tool exactly once", () => {
|
||||
expect(Object.keys(TOOL_EFFECTS).sort()).toEqual(
|
||||
TOOL_CONTRACTS.map(({ name }) => name).sort(),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps execution and device wording aligned with declared effects", () => {
|
||||
const undeclared = TOOL_CONTRACTS.filter(
|
||||
({ name, description }) =>
|
||||
EXECUTION_WORDING.test(description) &&
|
||||
!declaresForeignAuthority(name) &&
|
||||
EXECUTION_WORDING_EXCEPTIONS[name] === undefined,
|
||||
).map(({ name }) => name);
|
||||
expect(undeclared).toEqual([]);
|
||||
const staleExceptions = Object.keys(EXECUTION_WORDING_EXCEPTIONS).filter(
|
||||
(name) => {
|
||||
const contract = TOOL_CONTRACTS.find(
|
||||
(candidate) => candidate.name === name,
|
||||
);
|
||||
return (
|
||||
contract === undefined ||
|
||||
!EXECUTION_WORDING.test(contract.description) ||
|
||||
declaresForeignAuthority(name)
|
||||
);
|
||||
},
|
||||
);
|
||||
expect(staleExceptions).toEqual([]);
|
||||
});
|
||||
|
||||
it("marks foreign execution and device mutation as destructive", () => {
|
||||
const destructive = TOOL_CONTRACTS.filter(
|
||||
({ effects }) => effects.executesForeignCode || effects.mutatesDevice,
|
||||
);
|
||||
expect(destructive.map(({ name }) => name).sort()).toEqual([
|
||||
"capture_browser_scenario",
|
||||
"capture_electron_scenario",
|
||||
"capture_native_ui_scenario",
|
||||
"capture_process_scenario",
|
||||
"install_adb_package",
|
||||
"observe_native_calls",
|
||||
"push_adb_file",
|
||||
"start_adb_activity",
|
||||
"start_adb_app",
|
||||
"stop_adb_app",
|
||||
"uninstall_adb_package",
|
||||
]);
|
||||
for (const contract of destructive)
|
||||
expect(contract.annotations, contract.name).toMatchObject({
|
||||
readOnlyHint: false,
|
||||
destructiveHint: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("derives destructiveHint from each destructive effect alone", () => {
|
||||
const base = TOOL_EFFECTS["binary_session"];
|
||||
if (base === undefined) throw new Error("binary_session is unaudited");
|
||||
expect(annotationsFromEffects(base)).toEqual({
|
||||
readOnlyHint: true,
|
||||
destructiveHint: false,
|
||||
idempotentHint: true,
|
||||
openWorldHint: false,
|
||||
});
|
||||
for (const flag of [
|
||||
"mayDiscardData",
|
||||
"executesForeignCode",
|
||||
"mutatesDevice",
|
||||
] as const)
|
||||
expect(annotationsFromEffects({ ...base, [flag]: true }), flag).toEqual({
|
||||
readOnlyHint: false,
|
||||
destructiveHint: true,
|
||||
idempotentHint: true,
|
||||
openWorldHint: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("publishes the advertised annotations derived from canonical effects", () => {
|
||||
for (const contract of TOOL_CONTRACTS)
|
||||
expect(contract.annotations, contract.name).toEqual(
|
||||
annotationsFromEffects(contract.effects),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,17 @@ export interface ToolEffects {
|
||||
readonly launchesProcess: boolean;
|
||||
readonly accessesNetwork: boolean;
|
||||
readonly changesUiState: boolean;
|
||||
/** Can overwrite, clear, or drop state that the caller cannot recover from REA. */
|
||||
readonly mayDiscardData: boolean;
|
||||
/**
|
||||
* Runs or drives code REA does not own on the host: the analysis target, a
|
||||
* caller-selected executable, or the application loaded into one. Running
|
||||
* REA's own pinned helpers or operator-configured analysis engines does not
|
||||
* count.
|
||||
*/
|
||||
readonly executesForeignCode: boolean;
|
||||
/** Changes an attached Android device: packages, files, or running apps. */
|
||||
readonly mutatesDevice: boolean;
|
||||
readonly idempotent: boolean;
|
||||
}
|
||||
|
||||
@@ -27,6 +37,8 @@ const effects = (overrides: Partial<ToolEffects> = {}): ToolEffects => ({
|
||||
accessesNetwork: false,
|
||||
changesUiState: false,
|
||||
mayDiscardData: false,
|
||||
executesForeignCode: false,
|
||||
mutatesDevice: false,
|
||||
idempotent: true,
|
||||
...overrides,
|
||||
});
|
||||
@@ -178,6 +190,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
launchesProcess: true,
|
||||
writesFilesystem: true,
|
||||
accessesNetwork: true,
|
||||
mutatesDevice: true,
|
||||
idempotent: false,
|
||||
}),
|
||||
capture_adb_screen: effects({
|
||||
@@ -239,6 +252,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
accessesNetwork: true,
|
||||
mutatesDevice: true,
|
||||
idempotent: false,
|
||||
}),
|
||||
uninstall_adb_package: effects({
|
||||
@@ -246,6 +260,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
accessesNetwork: true,
|
||||
mutatesDevice: true,
|
||||
idempotent: false,
|
||||
}),
|
||||
start_adb_app: effects({
|
||||
@@ -253,6 +268,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
accessesNetwork: true,
|
||||
mutatesDevice: true,
|
||||
idempotent: false,
|
||||
}),
|
||||
start_adb_activity: effects({
|
||||
@@ -260,6 +276,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
accessesNetwork: true,
|
||||
mutatesDevice: true,
|
||||
idempotent: false,
|
||||
}),
|
||||
stop_adb_app: effects({
|
||||
@@ -267,6 +284,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
accessesNetwork: true,
|
||||
mutatesDevice: true,
|
||||
idempotent: false,
|
||||
}),
|
||||
search_android_classes: effects({
|
||||
@@ -294,6 +312,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
writesFilesystem: true,
|
||||
mayDiscardData: true,
|
||||
}),
|
||||
inspect_native_load_image: evidence,
|
||||
inspect_native_dispatch_metadata: evidence,
|
||||
@@ -330,11 +349,31 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
resolve_containing_procedure: evidence,
|
||||
search_procedures: evidence,
|
||||
search_strings: evidence,
|
||||
set_address_name: effects({ mutatesTarget: true, mutatesSession: true }),
|
||||
set_addresses_names: effects({ mutatesTarget: true, mutatesSession: true }),
|
||||
set_bookmark: effects({ mutatesTarget: true, mutatesSession: true }),
|
||||
set_comment: effects({ mutatesTarget: true, mutatesSession: true }),
|
||||
set_inline_comment: effects({ mutatesTarget: true, mutatesSession: true }),
|
||||
set_address_name: effects({
|
||||
mutatesTarget: true,
|
||||
mutatesSession: true,
|
||||
mayDiscardData: true,
|
||||
}),
|
||||
set_addresses_names: effects({
|
||||
mutatesTarget: true,
|
||||
mutatesSession: true,
|
||||
mayDiscardData: true,
|
||||
}),
|
||||
set_bookmark: effects({
|
||||
mutatesTarget: true,
|
||||
mutatesSession: true,
|
||||
mayDiscardData: true,
|
||||
}),
|
||||
set_comment: effects({
|
||||
mutatesTarget: true,
|
||||
mutatesSession: true,
|
||||
mayDiscardData: true,
|
||||
}),
|
||||
set_inline_comment: effects({
|
||||
mutatesTarget: true,
|
||||
mutatesSession: true,
|
||||
mayDiscardData: true,
|
||||
}),
|
||||
unset_bookmark: effects({
|
||||
mutatesTarget: true,
|
||||
mutatesSession: true,
|
||||
@@ -365,6 +404,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
accessesNetwork: true,
|
||||
changesUiState: true,
|
||||
mayDiscardData: true,
|
||||
executesForeignCode: true,
|
||||
idempotent: false,
|
||||
}),
|
||||
// The owned process can change files, show UI and use the network.
|
||||
@@ -374,6 +414,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
launchesProcess: true,
|
||||
accessesNetwork: true,
|
||||
changesUiState: true,
|
||||
executesForeignCode: true,
|
||||
idempotent: false,
|
||||
}),
|
||||
inspect_macho: nativeEvidence,
|
||||
@@ -419,6 +460,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
accessesNetwork: true,
|
||||
changesUiState: true,
|
||||
mayDiscardData: true,
|
||||
executesForeignCode: true,
|
||||
idempotent: false,
|
||||
}),
|
||||
list_electron_targets: browserEvidence,
|
||||
@@ -431,6 +473,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
accessesNetwork: true,
|
||||
changesUiState: true,
|
||||
mayDiscardData: true,
|
||||
executesForeignCode: true,
|
||||
idempotent: false,
|
||||
}),
|
||||
list_javascript_runtime_targets: browserEvidence,
|
||||
@@ -479,6 +522,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
writesFilesystem: true,
|
||||
launchesProcess: true,
|
||||
accessesNetwork: true,
|
||||
executesForeignCode: true,
|
||||
idempotent: false,
|
||||
}),
|
||||
compare_process_captures: sessionEvidence,
|
||||
@@ -506,9 +550,15 @@ export const annotationsFromEffects = (
|
||||
value.launchesProcess ||
|
||||
value.accessesNetwork ||
|
||||
value.changesUiState ||
|
||||
value.mayDiscardData
|
||||
value.mayDiscardData ||
|
||||
value.executesForeignCode ||
|
||||
value.mutatesDevice
|
||||
),
|
||||
destructiveHint: value.mayDiscardData,
|
||||
// MCP defines destructive as possibly non-additive changes to the
|
||||
// environment. Running foreign code or changing a device cannot be bounded
|
||||
// to additive effects, so either one is destructive even without data loss.
|
||||
destructiveHint:
|
||||
value.mayDiscardData || value.executesForeignCode || value.mutatesDevice,
|
||||
idempotentHint: value.idempotent,
|
||||
openWorldHint: value.launchesProcess || value.accessesNetwork,
|
||||
});
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { z } from "zod";
|
||||
import { evidenceBundleSummarySchema } from "../domain/evidenceRecordSummary.js";
|
||||
import { BINARY_ARCHITECTURES } from "../domain/binaryTargetTypes.js";
|
||||
import {
|
||||
binaryArchitectureSchema,
|
||||
rawBinaryEntryPointSchema,
|
||||
} from "../domain/rawBinary.js";
|
||||
import { nativeFunctionAnnotationsSchema } from "../domain/native/nativeFunctionAnnotations.js";
|
||||
import { nativeLoadImageSchema } from "../domain/native/nativeLoadImage.js";
|
||||
import { nativeUiResultSchema } from "../domain/native/nativeUiObservation.js";
|
||||
@@ -409,16 +413,33 @@ export const managedWorkflowOutputSchemas: Readonly<
|
||||
),
|
||||
};
|
||||
|
||||
const lifecycleTargetFields = {
|
||||
path: z.string(),
|
||||
kind: targetKindSchema,
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
architecture: z.enum(BINARY_ARCHITECTURES).nullable(),
|
||||
};
|
||||
const detectedLifecycleTargetSchema = z.object({
|
||||
...lifecycleTargetFields,
|
||||
format: targetFormatSchema.exclude(["raw-binary"]),
|
||||
});
|
||||
const rawLifecycleTargetSchema = z.object({
|
||||
...lifecycleTargetFields,
|
||||
format: z.literal("raw-binary"),
|
||||
kind: z.literal("executable"),
|
||||
architecture: binaryArchitectureSchema,
|
||||
entry_point: rawBinaryEntryPointSchema.describe(
|
||||
"Canonical caller-selected address where raw file offset 0 is mapped and execution is seeded.",
|
||||
),
|
||||
});
|
||||
|
||||
/** Exact structured-content schemas for target lifecycle operations. */
|
||||
export const sessionOutputSchemas = {
|
||||
open_binary: lifecycleResultOf(
|
||||
z.object({
|
||||
path: z.string(),
|
||||
format: targetFormatSchema,
|
||||
kind: targetKindSchema,
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
architecture: z.enum(BINARY_ARCHITECTURES).nullable(),
|
||||
}),
|
||||
z.discriminatedUnion("format", [
|
||||
detectedLifecycleTargetSchema,
|
||||
rawLifecycleTargetSchema,
|
||||
]),
|
||||
),
|
||||
close_binary: lifecycleResultOf(
|
||||
z.union([
|
||||
@@ -448,19 +469,15 @@ export const sessionOutputSchemas = {
|
||||
),
|
||||
binary_session: lifecycleResultOf(
|
||||
z.union([
|
||||
z.union([
|
||||
sessionProvider.extend({
|
||||
open: z.literal(false),
|
||||
}),
|
||||
sessionProvider.extend({
|
||||
open: z.literal(true),
|
||||
path: z.string(),
|
||||
format: targetFormatSchema,
|
||||
kind: targetKindSchema,
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
architecture: z.enum(BINARY_ARCHITECTURES).nullable(),
|
||||
}),
|
||||
]),
|
||||
sessionProvider.extend({ open: z.literal(false) }),
|
||||
sessionProvider.extend({
|
||||
open: z.literal(true),
|
||||
...detectedLifecycleTargetSchema.shape,
|
||||
}),
|
||||
sessionProvider.extend({
|
||||
open: z.literal(true),
|
||||
...rawLifecycleTargetSchema.shape,
|
||||
}),
|
||||
]),
|
||||
),
|
||||
export_evidence_bundle: lifecycleResultOf(
|
||||
|
||||
@@ -56,6 +56,7 @@ export const targetFormatSchema = z.enum([
|
||||
"pe",
|
||||
"dos-mz",
|
||||
"dos-com",
|
||||
"raw-binary",
|
||||
"zip",
|
||||
"ipa",
|
||||
"apk",
|
||||
@@ -292,6 +293,8 @@ const toolAvailabilityFacts = {
|
||||
accessesNetwork: z.boolean(),
|
||||
changesUiState: z.boolean(),
|
||||
mayDiscardData: z.boolean(),
|
||||
executesForeignCode: z.boolean(),
|
||||
mutatesDevice: z.boolean(),
|
||||
idempotent: z.boolean(),
|
||||
}),
|
||||
annotations: z.object({
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
snapshotBinding,
|
||||
snapshotEvidenceForQuery,
|
||||
snapshotTarget,
|
||||
snapshotMatchesTarget,
|
||||
} from "./analysisSnapshot.js";
|
||||
import {
|
||||
ANALYSIS_SNAPSHOT_PROFILE,
|
||||
@@ -16,6 +17,7 @@ import {
|
||||
} from "./analysisSnapshot.fixture.js";
|
||||
import { createEvidence } from "./evidence.js";
|
||||
import { createEvidenceBundle } from "./evidenceBundle.js";
|
||||
import type { BinaryTarget } from "./binaryTargetTypes.js";
|
||||
|
||||
const snapshotWithHistoricalEvidence = () => {
|
||||
const target = snapshotTarget(ANALYSIS_SNAPSHOT_TARGET);
|
||||
@@ -68,6 +70,54 @@ const snapshotWithHistoricalEvidence = () => {
|
||||
};
|
||||
|
||||
describe("analysis snapshot contract", () => {
|
||||
it("partitions raw snapshots and query identities by the canonical entry", () => {
|
||||
const target: BinaryTarget = {
|
||||
path: "/fixture/image.bin",
|
||||
sha256: ANALYSIS_SNAPSHOT_TARGET.sha256,
|
||||
kind: "executable",
|
||||
format: "raw-binary",
|
||||
architecture: "arm",
|
||||
availableArchitectures: ["arm"],
|
||||
entryPoint: "0x8000000",
|
||||
entryPointSource: "0x08000000",
|
||||
};
|
||||
const snapshot = snapshotTarget(target);
|
||||
const binding = snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE);
|
||||
const changed = {
|
||||
...target,
|
||||
entryPoint: "0x9000000",
|
||||
entryPointSource: "0x09000000",
|
||||
};
|
||||
expect(
|
||||
snapshotMatchesTarget(snapshot, {
|
||||
...target,
|
||||
entryPointSource: "0x8000000",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(snapshotMatchesTarget(snapshot, changed)).toBe(false);
|
||||
expect(analysisQueryId(snapshot, binding, "list_procedures", {})).not.toBe(
|
||||
analysisQueryId(snapshotTarget(changed), binding, "list_procedures", {}),
|
||||
);
|
||||
const parsed = analysisSnapshotSchema.parse({
|
||||
target: snapshot,
|
||||
binding,
|
||||
entries: [],
|
||||
workflow_entries: [],
|
||||
evidence_bundle: createEvidenceBundle([]),
|
||||
});
|
||||
expect(parsed.target).toHaveProperty("entry_point", target.entryPoint);
|
||||
const { entry_point: _entry, ...legacy } = {
|
||||
...snapshot,
|
||||
entry_point: target.entryPoint,
|
||||
};
|
||||
expect(
|
||||
analysisSnapshotSchema.safeParse({ ...parsed, target: legacy }).success,
|
||||
).toBe(false);
|
||||
expect(snapshotTarget(ANALYSIS_SNAPSHOT_TARGET)).not.toHaveProperty(
|
||||
"entry_point",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves DOS MZ target and subject formats with the x86 family", () => {
|
||||
const target = {
|
||||
path: ANALYSIS_SNAPSHOT_TARGET.path,
|
||||
@@ -113,6 +163,37 @@ describe("analysis snapshot contract", () => {
|
||||
expect(parsed.evidence_bundle.records[0]?.subject?.format).toBe("dos-mz");
|
||||
});
|
||||
|
||||
it("rejects a snapshot subject path containing NUL", () => {
|
||||
const binding = snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE);
|
||||
const entry = {
|
||||
query_id: `query_${"0".repeat(64)}`,
|
||||
operation: "analyze_function",
|
||||
parameters: {},
|
||||
execution: {
|
||||
result: null,
|
||||
raw_result: null,
|
||||
provider: binding.provider,
|
||||
limitations: [],
|
||||
locations: [],
|
||||
subject: {
|
||||
path: "a\u0000b",
|
||||
sha256: "a".repeat(64),
|
||||
format: "elf" as const,
|
||||
architecture: null,
|
||||
},
|
||||
},
|
||||
};
|
||||
expect(
|
||||
analysisSnapshotSchema.safeParse({
|
||||
target: snapshotTarget(ANALYSIS_SNAPSHOT_TARGET),
|
||||
binding,
|
||||
entries: [entry],
|
||||
workflow_entries: [],
|
||||
evidence_bundle: createEvidenceBundle([]),
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts snapshots with more than ten thousand analysis entries", () => {
|
||||
const binding = snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE);
|
||||
const entry = {
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
compareUnicodeCodePoints,
|
||||
compositeKey,
|
||||
} from "./unicodeCodePointOrder.js";
|
||||
import { localPathStringSchema } from "./localPath.js";
|
||||
|
||||
import {
|
||||
analysisProfileSchema,
|
||||
@@ -39,6 +40,7 @@ import { digestSchema } from "./../domain/digests.js";
|
||||
import { prefixedDigestSchema } from "./../domain/digests.js";
|
||||
import { canonicalJsonDigestSteps } from "./canonicalJsonDigestSteps.js";
|
||||
import { freezeJsonSnapshot } from "./immutableJson.js";
|
||||
import { rawBinaryEntryPointSchema } from "./rawBinary.js";
|
||||
|
||||
const architectureSchema = z.enum(BINARY_ARCHITECTURES);
|
||||
const formatSchema = z.enum([
|
||||
@@ -48,6 +50,7 @@ const formatSchema = z.enum([
|
||||
"pe",
|
||||
"dos-mz",
|
||||
"dos-com",
|
||||
"raw-binary",
|
||||
"zip",
|
||||
"ipa",
|
||||
"apk",
|
||||
@@ -65,7 +68,7 @@ const formatSchema = z.enum([
|
||||
]);
|
||||
const kindSchema = z.enum(["executable", "database", "archive", "artifact"]);
|
||||
const subjectSchema = z.object({
|
||||
path: z.string().min(1),
|
||||
path: localPathStringSchema,
|
||||
sha256: digestSchema,
|
||||
format: z.enum([
|
||||
...formatSchema.options,
|
||||
@@ -79,12 +82,22 @@ const subjectSchema = z.object({
|
||||
]),
|
||||
architecture: architectureSchema.nullable(),
|
||||
});
|
||||
const targetSchema = z.object({
|
||||
const targetIdentitySchema = z.object({
|
||||
sha256: digestSchema,
|
||||
kind: kindSchema,
|
||||
format: formatSchema,
|
||||
architecture: architectureSchema.nullable(),
|
||||
});
|
||||
const targetSchema = z.discriminatedUnion("format", [
|
||||
targetIdentitySchema.extend({
|
||||
format: z.enum(
|
||||
formatSchema.options.filter((format) => format !== "raw-binary"),
|
||||
),
|
||||
}),
|
||||
targetIdentitySchema.extend({
|
||||
format: z.literal("raw-binary"),
|
||||
entry_point: rawBinaryEntryPointSchema,
|
||||
}),
|
||||
]);
|
||||
const bindingSchema = z
|
||||
.object({
|
||||
provider: committedProviderSchema,
|
||||
@@ -310,12 +323,16 @@ const canonicalJson = (value: unknown): string => {
|
||||
/** Project a binary into the path-free identity used for cache invalidation. */
|
||||
export const snapshotTarget = (
|
||||
target: BinaryTarget,
|
||||
): AnalysisSnapshotTarget => ({
|
||||
sha256: target.sha256,
|
||||
kind: target.kind,
|
||||
format: target.format,
|
||||
architecture: target.architecture ?? null,
|
||||
});
|
||||
): AnalysisSnapshotTarget => {
|
||||
const identity = {
|
||||
sha256: target.sha256,
|
||||
kind: target.kind,
|
||||
architecture: target.architecture ?? null,
|
||||
};
|
||||
return target.format === "raw-binary"
|
||||
? { ...identity, format: target.format, entry_point: target.entryPoint }
|
||||
: { ...identity, format: target.format };
|
||||
};
|
||||
|
||||
/** Build the immutable provider/profile binding used by a cached snapshot. */
|
||||
export const snapshotBinding = (
|
||||
@@ -334,7 +351,10 @@ export const snapshotMatchesTarget = (
|
||||
snapshot.sha256 === target.sha256 &&
|
||||
snapshot.kind === target.kind &&
|
||||
snapshot.format === target.format &&
|
||||
snapshot.architecture === (target.architecture ?? null);
|
||||
snapshot.architecture === (target.architecture ?? null) &&
|
||||
(snapshot.format !== "raw-binary" ||
|
||||
(target.format === "raw-binary" &&
|
||||
snapshot.entry_point === target.entryPoint));
|
||||
|
||||
/** Compare a snapshot binding with the selected concrete analysis profile. */
|
||||
export const snapshotMatchesProfile = (
|
||||
|
||||
@@ -50,6 +50,7 @@ const artifactFormatSchema = z.enum([
|
||||
"pe",
|
||||
"dos-mz",
|
||||
"dos-com",
|
||||
"raw-binary",
|
||||
"hopper",
|
||||
"analysis-database",
|
||||
"ipa",
|
||||
|
||||
@@ -78,6 +78,13 @@ export type BinaryTarget =
|
||||
readonly executableRole?: never;
|
||||
readonly managed?: never;
|
||||
})
|
||||
| (ExecutableTarget & {
|
||||
readonly format: "raw-binary";
|
||||
readonly entryPoint: string;
|
||||
readonly entryPointSource: string;
|
||||
readonly executableRole?: never;
|
||||
readonly managed?: never;
|
||||
})
|
||||
| (ExecutableTarget & {
|
||||
readonly format: "pe";
|
||||
/** Provider-neutral PE image role observed from COFF characteristics. */
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { z } from "zod";
|
||||
import { err, ok, type Result } from "./result.js";
|
||||
|
||||
/** Headerless DOS COM interpretation explicitly selected by the caller. */
|
||||
export const executableFormatHintSchema = z.literal("dos-com");
|
||||
/** Headerless executable interpretation explicitly selected by the caller. */
|
||||
export const executableFormatHintSchema = z.enum(["dos-com", "raw-binary"]);
|
||||
/** Explicit executable interpretation for formats with no identifying header. */
|
||||
export type ExecutableFormatHint = z.infer<typeof executableFormatHintSchema>;
|
||||
|
||||
|
||||
@@ -291,6 +291,22 @@ describe("analysis evidence identity", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a subject local path containing NUL while admitting an empty path", () => {
|
||||
const evidence = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: {},
|
||||
result: true,
|
||||
});
|
||||
expect(evidence.subject).not.toBeNull();
|
||||
const withPath = (path: string) => ({
|
||||
...evidence,
|
||||
subject: { ...evidence.subject, local_path: path },
|
||||
});
|
||||
expect(evidenceSchema.safeParse(withPath("/tmp/fixture")).success).toBe(true);
|
||||
expect(evidenceSchema.safeParse(withPath("")).success).toBe(true);
|
||||
expect(evidenceSchema.safeParse(withPath("a\u0000b")).success).toBe(false);
|
||||
});
|
||||
|
||||
it("binds an explicit unknown-subject reason into the semantic Evidence identity", () => {
|
||||
const reason = "Caller excluded the observed digest.";
|
||||
const observation = { operation: "health", parameters: {}, result: true };
|
||||
|
||||
@@ -2,6 +2,7 @@ import { z } from "zod";
|
||||
|
||||
import { digestCanonicalValue } from "./canonicalDigest.js";
|
||||
import { canonicalJsonDigestSteps } from "./canonicalJsonDigestSteps.js";
|
||||
import { nulFreeStringSchema } from "./localPath.js";
|
||||
|
||||
import {
|
||||
analysisProfileSchema,
|
||||
@@ -43,6 +44,7 @@ const subjectSchema = z.object({
|
||||
"pe",
|
||||
"dos-mz",
|
||||
"dos-com",
|
||||
"raw-binary",
|
||||
"zip",
|
||||
"ipa",
|
||||
"apk",
|
||||
@@ -65,7 +67,7 @@ const subjectSchema = z.object({
|
||||
"entitlements",
|
||||
]),
|
||||
architecture: z.enum(BINARY_ARCHITECTURES).nullable(),
|
||||
local_path: z.string(),
|
||||
local_path: nulFreeStringSchema,
|
||||
});
|
||||
/** Source location attached to an evidence observation. */
|
||||
/** Source-location schema shared by evidence-bearing persistence formats. */
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ROLLDOWN_MODULE_INTEROP } from "./javascriptModuleInterop.fixture.js";
|
||||
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
|
||||
|
||||
const CAPTURED_INTEROP = ROLLDOWN_MODULE_INTEROP.replace(
|
||||
"__defProp = Object.defineProperty",
|
||||
"__defProp = define",
|
||||
);
|
||||
const WINDOW = `let electron = require("electron");
|
||||
electron = __toESM(electron, 1); new electron.BrowserWindow({});`;
|
||||
|
||||
describe("captured intrinsic invocation reads", () => {
|
||||
it.each([
|
||||
'(0, Object.defineProperty.call)(null,Object,"create",{value:replacement});',
|
||||
'(0, Object.defineProperty.apply)(null,[Object,"create",{value:replacement}]);',
|
||||
])(
|
||||
"does not invent a receiver for a detached invocation member: %s",
|
||||
(invoke) => {
|
||||
const result = analyzeJavaScriptStaticSource(`
|
||||
${invoke}
|
||||
${ROLLDOWN_MODULE_INTEROP} ${WINDOW}
|
||||
`);
|
||||
expect(result.electron.browser_windows).toHaveLength(1);
|
||||
},
|
||||
);
|
||||
|
||||
it("retains callee-prefix effects before classifying the invocation", () => {
|
||||
const result = analyzeJavaScriptStaticSource(`
|
||||
const define = Object.defineProperty;
|
||||
const metadata = {};
|
||||
(Object.defineProperty = replacement, Object.defineProperty)(metadata,"x",{value:1});
|
||||
${CAPTURED_INTEROP} ${WINDOW}
|
||||
`);
|
||||
expect(result.electron.browser_windows).toEqual([]);
|
||||
});
|
||||
|
||||
it("retains a callee selected before an argument replaces its global property", () => {
|
||||
const result = analyzeJavaScriptStaticSource(`
|
||||
const define = Object.defineProperty;
|
||||
const metadata = {};
|
||||
Object.defineProperty(metadata,"x",(Object.defineProperty = replacement,{value:1}));
|
||||
${CAPTURED_INTEROP} ${WINDOW}
|
||||
`);
|
||||
expect(result.electron.browser_windows).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'define.call(null,metadata,"x",{value:1});',
|
||||
'define.apply(null,[metadata,"x",{value:1}]);',
|
||||
'const change = define.bind(null,metadata,"x"); change({value:1});',
|
||||
'const also = define; also.call(null,metadata,"x",{value:1});',
|
||||
])("retains a function captured before global replacement: %s", (invoke) => {
|
||||
const result = analyzeJavaScriptStaticSource(`
|
||||
const define = Object.defineProperty;
|
||||
Object.defineProperty = replacement;
|
||||
const metadata = {}; ${invoke}
|
||||
${CAPTURED_INTEROP} ${WINDOW}
|
||||
`);
|
||||
expect(result.electron.browser_windows).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["call", 'define.call(null,metadata,"x",{value:1});'],
|
||||
["apply", 'define.apply(null,[metadata,"x",{value:1}]);'],
|
||||
[
|
||||
"bind",
|
||||
'const change = define.bind(null,metadata,"x"); change({value:1});',
|
||||
],
|
||||
])(
|
||||
"checks the later %s property read on a captured function",
|
||||
(method, invoke) => {
|
||||
for (const owner of ["define", "Function.prototype"]) {
|
||||
const result = analyzeJavaScriptStaticSource(`
|
||||
const define = Object.defineProperty;
|
||||
${owner}.${method} = replacement;
|
||||
const metadata = {}; ${invoke}
|
||||
${CAPTURED_INTEROP} ${WINDOW}
|
||||
`);
|
||||
expect(result.electron.browser_windows, owner).toEqual([]);
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,667 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
|
||||
import { ROLLDOWN_MODULE_INTEROP } from "./javascriptModuleInterop.fixture.js";
|
||||
|
||||
const WINDOW =
|
||||
'new electron.BrowserWindow({webPreferences:{preload:"./preload.js"}});';
|
||||
const IMPORT = 'let electron = require("electron");';
|
||||
const WRAP = "electron = __toESM(electron, 1);";
|
||||
// The upstream runtime uses control-body braces that its bundled printer omits.
|
||||
// https://github.com/rolldown/rolldown/blob/22a0ab13732d81f2559ad2b7064b688699324889/crates/rolldown/src/runtime/runtime-base.js
|
||||
const BLOCK_MODULE_INTEROP = ROLLDOWN_MODULE_INTEROP.replace(
|
||||
'if (from && typeof from === "object" || typeof from === "function") for',
|
||||
'if (from && typeof from === "object" || typeof from === "function") { for',
|
||||
)
|
||||
.replace(
|
||||
"if (!__hasOwnProp.call(to, key) && key !== except) __defProp",
|
||||
"if (!__hasOwnProp.call(to, key) && key !== except) { __defProp",
|
||||
)
|
||||
.replace(" });", " });\n }")
|
||||
.replace(" return to;", " }\n return to;");
|
||||
|
||||
describe("Electron module interop identity", () => {
|
||||
it("preserves named APIs through the released Rolldown namespace conversion", () => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`${ROLLDOWN_MODULE_INTEROP}
|
||||
${IMPORT} ${WRAP} ${WINDOW}
|
||||
new electron.BrowserWindow({webPreferences:{preload:runtimePath}});
|
||||
electron.ipcMain.handle("ping", () => "pong");
|
||||
electron.contextBridge.exposeInMainWorld("api", {ping:true});
|
||||
`);
|
||||
expect(analysis.electron.browser_windows).toMatchObject([
|
||||
{ preload_path: "./preload.js" },
|
||||
{ preload_path: null },
|
||||
]);
|
||||
expect(analysis.electron.ipc).toMatchObject([
|
||||
{ channel: "ping", side: "main" },
|
||||
]);
|
||||
expect(analysis.electron.context_bridge_apis).toMatchObject([
|
||||
{ api_key: "api" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("follows lexical identities when helper and parameter names change", () => {
|
||||
const source = `${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP} ${WINDOW}`
|
||||
.replaceAll("__toESM", "namespaceOf")
|
||||
.replaceAll("__copyProps", "copyNamed")
|
||||
.replaceAll("mod", "inputModule")
|
||||
.replaceAll("isNodeMode", "nodeMode")
|
||||
.replaceAll("target", "namespaceTarget")
|
||||
.replaceAll("from", "sourceObject");
|
||||
expect(
|
||||
analyzeJavaScriptStaticSource(source).electron.browser_windows,
|
||||
).toMatchObject([{ preload_path: "./preload.js" }]);
|
||||
});
|
||||
|
||||
it("preserves the same operations through control-body braces", () => {
|
||||
expect(
|
||||
analyzeJavaScriptStaticSource(
|
||||
`${BLOCK_MODULE_INTEROP}\n${IMPORT} ${WRAP} ${WINDOW}`,
|
||||
).electron.browser_windows,
|
||||
).toMatchObject([{ preload_path: "./preload.js" }]);
|
||||
});
|
||||
|
||||
it("keeps additional operations inside a control block unresolved", () => {
|
||||
const altered = BLOCK_MODULE_INTEROP.replace(
|
||||
"{ __defProp",
|
||||
"{ from = unrelated; __defProp",
|
||||
);
|
||||
expect(
|
||||
analyzeJavaScriptStaticSource(`${altered}\n${IMPORT} ${WRAP} ${WINDOW}`)
|
||||
.electron.browser_windows,
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
const BOUND_INTRINSIC_MUTATIONS: [string, string][] = [
|
||||
[
|
||||
"intrinsic changed through aliased prebound arguments",
|
||||
`const objectAlias = Object; const key = "create"; const define = Object.defineProperty; const mutate = define.bind(null, objectAlias, key); mutate({value:customCreate}); ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"intrinsic changed through nested prebinding",
|
||||
`const first = Object.defineProperty.bind(null, Object); const second = first.bind(null, "create"); second({value:customCreate}); ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"a replaced bound mutator bind method is unknown",
|
||||
`const first = Object.defineProperty.bind(null, Object); first.bind = customBind; const second = first.bind(null, "create"); second({value:customCreate}); ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"intrinsic changed through a computed prebound call",
|
||||
`const mutate = Object.defineProperty.bind(null, Object, "create"); mutate["call"](null, {value:customCreate}); ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"intrinsic changed through a computed prebound apply",
|
||||
`const mutate = Object.defineProperty.bind(null, Object, "create"); mutate["apply"](null, [{value:customCreate}]); ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"a replaced bind intrinsic makes a prebound mutator unknown",
|
||||
`Function.prototype.bind = customBind; const mutate = Object.defineProperty.bind(null, Object, "create"); mutate({value:customCreate}); ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
];
|
||||
|
||||
describe("Electron module interop uncertainty", () => {
|
||||
it.each([
|
||||
...BOUND_INTRINSIC_MUTATIONS,
|
||||
[
|
||||
"intrinsic changed through an unresolved mutator target",
|
||||
`Object.defineProperty(getTarget(), "create", {value:customCreate}); ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"intrinsic changed via dynamic apply",
|
||||
`const args = [Object, "getOwnPropertyNames", {value:() => []}]; Object.defineProperty.apply(null, args); ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"intrinsic changed via spread call",
|
||||
`const args = [Object, "getOwnPropertyNames", {value:() => []}]; Object.defineProperty.call(null, ...args); ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"intrinsic changed via Reflect.apply",
|
||||
`const args = [Object, "getOwnPropertyNames", {value:() => []}]; Reflect.apply(Object.defineProperty, null, args); ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"intrinsic changed via spread Reflect.apply",
|
||||
`const args = [null, [Object, "create", {value:customCreate}]]; Reflect.apply(Object.defineProperty, ...args); ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"intrinsic changed via call",
|
||||
`Object.defineProperty.call(null, Object, "getOwnPropertyNames", {value:() => []}); ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"intrinsic changed via apply",
|
||||
`Object.defineProperty.apply(null, [Object, "getOwnPropertyNames", {value:() => []}]); ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"intrinsic changed with defineProperty",
|
||||
`Object.defineProperty(Object, "getOwnPropertyNames", {value:() => []}); ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"intrinsic changed with Reflect.set",
|
||||
`Reflect.set(Object, "getOwnPropertyNames", () => []); ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"intrinsic changed with an aliased mutator",
|
||||
`const change = Object.defineProperty; change(Object, "create", {value:customCreate}); ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"intrinsic changed with assign",
|
||||
`Object.assign(Object, {getOwnPropertyNames:() => []}); ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"intrinsic changed with defineProperties",
|
||||
`Object.defineProperties(Function.prototype, {bind:{value:customBind}}); ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"overwritten Object global",
|
||||
`Object = customObject; ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"overwritten intrinsic through an alias",
|
||||
`const objectAlias = Object; objectAlias.create = customCreate; ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"overwritten intrinsic through globalThis",
|
||||
`globalThis.Object.create = customCreate; ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"helper called before initialization",
|
||||
`${IMPORT} ${WRAP} ${ROLLDOWN_MODULE_INTEROP}`,
|
||||
],
|
||||
[
|
||||
"fake helper",
|
||||
`${ROLLDOWN_MODULE_INTEROP}\n__toESM = (mod) => ({BrowserWindow:Fake}); ${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"changed getter",
|
||||
`${ROLLDOWN_MODULE_INTEROP.replace("from[k]", "to[k]")}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"replaced copy helper",
|
||||
`${ROLLDOWN_MODULE_INTEROP}\n__copyProps = () => ({}); ${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"replaced intrinsic alias",
|
||||
`${ROLLDOWN_MODULE_INTEROP}\n__defProp = () => ({}); ${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"shadowed Object",
|
||||
`const Object = customObject; ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"overwritten intrinsic",
|
||||
`Object.create = customCreate; ${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"overwritten alias call",
|
||||
`${ROLLDOWN_MODULE_INTEROP}\n__hasOwnProp.call = customCall; ${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"overwritten Function bind",
|
||||
`${ROLLDOWN_MODULE_INTEROP}\nFunction.prototype.bind = customBind; ${IMPORT} ${WRAP}`,
|
||||
],
|
||||
[
|
||||
"conditional conversion",
|
||||
`${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} if (flag) { ${WRAP} }`,
|
||||
],
|
||||
[
|
||||
"compound assignment",
|
||||
`${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} electron ||= __toESM(electron, 1);`,
|
||||
],
|
||||
[
|
||||
"other input",
|
||||
`${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} electron = __toESM(other, 1);`,
|
||||
],
|
||||
[
|
||||
"later overwrite",
|
||||
`${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP} electron = unrelated;`,
|
||||
],
|
||||
[
|
||||
"overwritten constructor",
|
||||
`${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP} electron.BrowserWindow = Fake;`,
|
||||
],
|
||||
])("does not infer Electron identity after %s", (_name, setup) => {
|
||||
expect(
|
||||
analyzeJavaScriptStaticSource(`${setup}\n${WINDOW}`).electron
|
||||
.browser_windows,
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Electron module interop helper results", () => {
|
||||
it.each([
|
||||
'const {BrowserWindow} = __toESM(require("electron"), 1); new BrowserWindow({});',
|
||||
'const {BrowserWindow: Window} = __toESM(require("electron"), 1); new Window({});',
|
||||
'const {default: {BrowserWindow}} = __toESM(require("electron"), 1); new BrowserWindow({});',
|
||||
'const Window = __toESM(require("electron"), 1).BrowserWindow; new Window({});',
|
||||
])("preserves a proven result projection: %s", (source) => {
|
||||
expect(
|
||||
analyzeJavaScriptStaticSource(`${ROLLDOWN_MODULE_INTEROP}\n${source}`)
|
||||
.electron.browser_windows,
|
||||
).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'const {[key]: Window} = __toESM(require("electron"), 1); new Window({});',
|
||||
'const {...electron} = __toESM(require("electron"), 1); new electron.BrowserWindow({});',
|
||||
'let {BrowserWindow} = __toESM(require("electron"), 1); BrowserWindow = Fake; new BrowserWindow({});',
|
||||
])("keeps an uncertain result projection unresolved: %s", (source) => {
|
||||
expect(
|
||||
analyzeJavaScriptStaticSource(`${ROLLDOWN_MODULE_INTEROP}\n${source}`)
|
||||
.electron.browser_windows,
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"",
|
||||
", 0",
|
||||
", false",
|
||||
", true",
|
||||
", 1",
|
||||
', "node"',
|
||||
', ""',
|
||||
", null",
|
||||
])("preserves named exports with a literal node mode: %s", (mode) => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`${ROLLDOWN_MODULE_INTEROP}
|
||||
const fresh = __toESM(require("electron")${mode});
|
||||
new fresh.BrowserWindow({});
|
||||
const {BrowserWindow} = __toESM(require("electron")${mode});
|
||||
new BrowserWindow({});
|
||||
let electron = require("electron");
|
||||
electron = __toESM(electron${mode}); ${WINDOW}
|
||||
`);
|
||||
expect(analysis.electron.browser_windows).toHaveLength(3);
|
||||
});
|
||||
|
||||
it.each(["", ", 0", ", false"])(
|
||||
"does not assume a module-valued default with node mode: %s",
|
||||
(mode) => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`${ROLLDOWN_MODULE_INTEROP}
|
||||
const original = require("electron");
|
||||
original.__esModule = true;
|
||||
original.default = {BrowserWindow: Fake};
|
||||
const {default: {BrowserWindow}} = __toESM(require("electron")${mode});
|
||||
new BrowserWindow({});
|
||||
const other = __toESM(require("electron")${mode}).default;
|
||||
new other.BrowserWindow({});
|
||||
new (__toESM(require("electron")${mode}).default.BrowserWindow)({});
|
||||
`);
|
||||
expect(analysis.electron.browser_windows).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["__toESM", "identity"])(
|
||||
"rejects side-effecting extra arguments to %s",
|
||||
(helper) => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`${ROLLDOWN_MODULE_INTEROP}
|
||||
function identity(mod) { return mod; }
|
||||
const electron = ${helper}(require("electron"), mutate()); ${WINDOW}
|
||||
`);
|
||||
expect(analysis.electron.browser_windows).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
"const __toESM = () => ({BrowserWindow:FakeWindow});",
|
||||
"const __toESM = async (mod) => mod;",
|
||||
"function* __toESM(mod) { return mod; }",
|
||||
"const __toESM = (this && this.__toESM) || ((mod) => mod);",
|
||||
])("keeps an unproven fresh result unresolved: %s", (helper) => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`${helper}
|
||||
const electron = __toESM(require("electron"), 1); ${WINDOW}
|
||||
new (__toESM(require("electron"), 1)).BrowserWindow({});
|
||||
`);
|
||||
expect(analysis.electron.browser_windows).toEqual([]);
|
||||
});
|
||||
|
||||
it("preserves a proven fresh namespace and a pure identity helper", () => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`${ROLLDOWN_MODULE_INTEROP}
|
||||
const electron = __toESM(require("electron"), 1); ${WINDOW}
|
||||
new (__toESM(require("electron"), 1)).BrowserWindow({});
|
||||
function passthrough(value) {return value;}
|
||||
const plain = passthrough(require("electron"));
|
||||
new plain.BrowserWindow({});
|
||||
`);
|
||||
expect(analysis.electron.browser_windows).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Electron module interop pattern writes", () => {
|
||||
it.each([
|
||||
"({Object} = replacements);",
|
||||
"[Function] = replacements;",
|
||||
"({nested:{Object}} = replacements);",
|
||||
"({replacement:Object = customObject} = replacements);",
|
||||
"({...Object} = replacements);",
|
||||
"[...Function] = replacements;",
|
||||
"for ({Object} of replacements) {}",
|
||||
"for ([Function] in replacements) {}",
|
||||
])("rejects an intrinsic replaced through %s", (write) => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`
|
||||
${write} ${ROLLDOWN_MODULE_INTEROP} ${IMPORT} ${WRAP} ${WINDOW}
|
||||
`);
|
||||
expect(analysis.parse_error_count).toBe(0);
|
||||
expect(analysis.electron.browser_windows).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"({Object:unrelated} = replacements);",
|
||||
"function decoy(Object) {({Object} = replacements);}",
|
||||
])("preserves intrinsic identity for an unrelated target: %s", (write) => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`
|
||||
${write} ${ROLLDOWN_MODULE_INTEROP} ${IMPORT} ${WRAP} ${WINDOW}
|
||||
`);
|
||||
expect(analysis.parse_error_count).toBe(0);
|
||||
expect(analysis.electron.browser_windows).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("preserves captured operations after later property destructuring", () => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`
|
||||
${ROLLDOWN_MODULE_INTEROP} ({create:Object.create} = replacements);
|
||||
${IMPORT} ${WRAP} ${WINDOW}
|
||||
`);
|
||||
expect(analysis.electron.browser_windows).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Electron module interop intrinsic captures", () => {
|
||||
it.each([
|
||||
"var captured = Object.defineProperty;",
|
||||
"const {defineProperty:captured} = Object;",
|
||||
"var first = Object.defineProperty; const captured = first;",
|
||||
])("retains the original function capture through %s", (capture) => {
|
||||
const runtime = ROLLDOWN_MODULE_INTEROP.replace(
|
||||
"__defProp = Object.defineProperty",
|
||||
"__defProp = captured",
|
||||
);
|
||||
const analysis = analyzeJavaScriptStaticSource(`
|
||||
${capture} Object.defineProperty = custom;
|
||||
${runtime} ${IMPORT} ${WRAP} ${WINDOW}
|
||||
`);
|
||||
expect(analysis.electron.browser_windows).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each(["var", "const"])(
|
||||
"keeps an intrinsic alias read before its %s initializer unresolved",
|
||||
(kind) => {
|
||||
const runtime = ROLLDOWN_MODULE_INTEROP.replace(
|
||||
"__defProp = Object.defineProperty",
|
||||
"__defProp = later",
|
||||
);
|
||||
const analysis = analyzeJavaScriptStaticSource(`
|
||||
${runtime} ${kind} later = Object.defineProperty;
|
||||
${IMPORT} ${WRAP} ${WINDOW}
|
||||
`);
|
||||
expect(analysis.electron.browser_windows).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it("requires the helper's intrinsic binding to initialize before conversion", () => {
|
||||
const runtime = ROLLDOWN_MODULE_INTEROP.replace(
|
||||
"var __defProp = Object.defineProperty;",
|
||||
"",
|
||||
);
|
||||
const analysis = analyzeJavaScriptStaticSource(`
|
||||
var captured = Object.defineProperty;
|
||||
${runtime} ${IMPORT} ${WRAP} ${WINDOW}
|
||||
var __defProp = captured;
|
||||
`);
|
||||
expect(analysis.electron.browser_windows).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Electron module interop capture and scope", () => {
|
||||
it.each(["metadata", "alias"])(
|
||||
"recognizes a hoisted function target through %s",
|
||||
(target) => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`
|
||||
const alias = metadata;
|
||||
Object.defineProperty(${target}, "x", {value:1});
|
||||
function metadata() {}
|
||||
${ROLLDOWN_MODULE_INTEROP} ${IMPORT} ${WRAP} ${WINDOW}
|
||||
`);
|
||||
expect(analysis.electron.browser_windows).toHaveLength(1);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
"var metadata = function () {};",
|
||||
"const metadata = () => {};",
|
||||
"class metadata {}",
|
||||
])("does not hoist fresh targets from %s", (declaration) => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`
|
||||
Object.defineProperty(metadata, "x", {value:1});
|
||||
${declaration}
|
||||
${ROLLDOWN_MODULE_INTEROP} ${IMPORT} ${WRAP} ${WINDOW}
|
||||
`);
|
||||
expect(analysis.electron.browser_windows).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'const {defineProperty:change} = Object; change(Object,"create",{value:customCreate});',
|
||||
"const objectAlias = Object; const {assign:change} = objectAlias; change(Object,{create:customCreate});",
|
||||
'const {set:change} = Reflect; change(Object,"create",customCreate);',
|
||||
'const {Object:{defineProperty:change}} = globalThis; change(Object,"create",{value:customCreate});',
|
||||
])("rejects a projected intrinsic mutator alias: %s", (write) => {
|
||||
const source = `${write} ${ROLLDOWN_MODULE_INTEROP}
|
||||
${IMPORT} ${WRAP} ${WINDOW}
|
||||
`.replaceAll("__toESM", "namespaceOf");
|
||||
const analysis = analyzeJavaScriptStaticSource(source);
|
||||
expect(analysis.parse_error_count).toBe(0);
|
||||
expect(analysis.electron.browser_windows).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"const metadata = {};",
|
||||
"const metadata = [];",
|
||||
"const initial = {}; const metadata = initial;",
|
||||
"const metadata = () => {};",
|
||||
"const metadata = function () {};",
|
||||
"const metadata = async () => {};",
|
||||
"const metadata = function* () {};",
|
||||
"const metadata = class {};",
|
||||
"const metadata = /local/;",
|
||||
"function metadata() {}",
|
||||
"class metadata {}",
|
||||
])(
|
||||
"keeps a fresh mutator target separate from intrinsic identity: %s",
|
||||
(setup) => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`
|
||||
${setup} Object.defineProperty(metadata,"x",{value:1});
|
||||
${ROLLDOWN_MODULE_INTEROP} ${IMPORT} ${WRAP} ${WINDOW}
|
||||
`);
|
||||
expect(analysis.electron.browser_windows).toHaveLength(1);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
"const metadata = getMetadata();",
|
||||
"let metadata = {}; metadata = Object;",
|
||||
"Object.defineProperty(metadata,'x',{value:1}); const metadata = {};",
|
||||
"const metadata = {intrinsic:Object}; Object.defineProperty(metadata.intrinsic,'create',{value:customCreate});",
|
||||
"const metadata = class {static {Object.create = customCreate;}};",
|
||||
"@(() => Object) class metadata {}",
|
||||
])("keeps an unproven mutator target unresolved: %s", (setup) => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`
|
||||
${setup} Object.defineProperty(metadata,"x",{value:1});
|
||||
${ROLLDOWN_MODULE_INTEROP} ${IMPORT} ${WRAP} ${WINDOW}
|
||||
`);
|
||||
expect(analysis.electron.browser_windows).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not reject unrelated intrinsic property definitions", () => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`
|
||||
Object.defineProperty(Object, "unrelated", {value:1});
|
||||
${ROLLDOWN_MODULE_INTEROP} ${IMPORT} ${WRAP} ${WINDOW}
|
||||
`);
|
||||
expect(analysis.electron.browser_windows).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("keeps opaque targets in a generic helper separate from outer module identity", () => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`
|
||||
function genericAssign() { Object.assign.apply(null, arguments); }
|
||||
${ROLLDOWN_MODULE_INTEROP} ${IMPORT} ${WRAP} ${WINDOW}
|
||||
`);
|
||||
expect(analysis.electron.browser_windows).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("rejects an opaque intrinsic mutation in the namespace's own callable", () => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`${ROLLDOWN_MODULE_INTEROP}
|
||||
function openWindow(args) {
|
||||
Object.defineProperty.apply(null, args);
|
||||
${IMPORT} ${WRAP} ${WINDOW}
|
||||
}
|
||||
`);
|
||||
expect(analysis.electron.browser_windows).toEqual([]);
|
||||
});
|
||||
|
||||
it("preserves captured intrinsics across later vendor polyfills and callable writes", () => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`${ROLLDOWN_MODULE_INTEROP}
|
||||
Object.create = customCreate;
|
||||
${IMPORT} ${WRAP}
|
||||
function runLoop(key) { globalThis[key] = this; }
|
||||
function polyfill() { Object.create = customCreate; }
|
||||
${WINDOW}
|
||||
`);
|
||||
expect(analysis.electron.browser_windows).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("keeps a shadowed namespace separate from the converted module", () => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`${ROLLDOWN_MODULE_INTEROP}
|
||||
${IMPORT} ${WRAP} ${WINDOW}
|
||||
function decoy(electron) { ${WINDOW} }
|
||||
`);
|
||||
expect(analysis.electron.browser_windows).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Electron module interop generic invocations", () => {
|
||||
it.each([
|
||||
'const change = Function.prototype.call.bind(Object.defineProperty); change(null,Object,"create",{value:customCreate});',
|
||||
'const call = Function.prototype.call; const change = call.bind(Object.defineProperty); change(null,Object,"create",{value:customCreate});',
|
||||
'const change = Function.prototype.call.bind(Object.defineProperty,null,Object,"create"); change({value:customCreate});',
|
||||
'Function.prototype.call.apply(Object.defineProperty,[null,Object,"create",{value:customCreate}]);',
|
||||
'Reflect.apply(Function.prototype.call,Object.defineProperty,[null,Object,"create",{value:customCreate}]);',
|
||||
'const change = Function.prototype.apply.bind(Object.defineProperty); change(null,[Object,"create",{value:customCreate}]);',
|
||||
'Reflect.apply(Function.prototype.apply,Object.defineProperty,[null,[Object,"create",{value:customCreate}]]);',
|
||||
'const first = Function.prototype.call.bind(Object.defineProperty,null,Object,"create"); const change = first.bind(fake); change({value:customCreate});',
|
||||
"const change = Function.prototype.call.bind(Object.defineProperty); change(null,...args);",
|
||||
"const change = Function.prototype.apply.bind(Object.defineProperty); change(null,args);",
|
||||
'const change = Function.prototype.call.bind(Object.defineProperty,null,...args); change(metadata,"x",{value:1});',
|
||||
'Function.prototype.call.call.call(Object.defineProperty,null,Object,"create",{value:customCreate});',
|
||||
'Object.defineProperty.call.call(Object.defineProperty,null,Object,"create",{value:customCreate});',
|
||||
'Function.prototype.apply.apply(Object.defineProperty,[null,[Object,"create",{value:customCreate}]]);',
|
||||
'const change = Object.defineProperty.call.bind(Object.defineProperty); change(null,Object,"create",{value:customCreate});',
|
||||
'const change = Function.prototype.call.call.bind(Object.defineProperty,null,Object,"create"); change({value:customCreate});',
|
||||
])("follows the callable receiver of a generic invocation: %s", (write) => {
|
||||
expect(
|
||||
analyzeJavaScriptStaticSource(
|
||||
`${write}\n${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP} ${WINDOW}`,
|
||||
).electron.browser_windows,
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'const change = Function.prototype.call.bind(Object.defineProperty); change(null,metadata,"x",{value:1});',
|
||||
'const change = Function.prototype.call.bind(Object.defineProperty,null,metadata,"x"); change({value:1});',
|
||||
'Function.prototype.call.call(Object.defineProperty,null,metadata,"x",{value:1});',
|
||||
'const change = Function.prototype.apply.bind(Object.defineProperty); change(null,[metadata,"x",{value:1}]);',
|
||||
'Reflect.apply(Function.prototype.apply,Object.defineProperty,[null,[metadata,"x",{value:1}]]);',
|
||||
'Function.prototype.call.call.call(Object.defineProperty,null,metadata,"x",{value:1});',
|
||||
'Function.prototype.apply.apply(Object.defineProperty,[null,[metadata,"x",{value:1}]]);',
|
||||
'const change = Object.defineProperty.call.bind(Object.defineProperty); change(null,metadata,"x",{value:1});',
|
||||
])("preserves fresh targets through a generic invocation: %s", (write) => {
|
||||
expect(
|
||||
analyzeJavaScriptStaticSource(
|
||||
`const metadata = {}; ${write}\n${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP} ${WINDOW}`,
|
||||
).electron.browser_windows,
|
||||
).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Electron module interop bound mutators", () => {
|
||||
it.each([
|
||||
'const change = Object.defineProperty.bind(null); change(Object,"create",{value:customCreate});',
|
||||
'const change = Object.defineProperty.bind(null,Object,"create"); change({value:customCreate});',
|
||||
'const first = Object.defineProperty.bind(null,Object); const change = first; change("create",{value:customCreate});',
|
||||
'const change = Object.defineProperty.bind(null,Object); change.call(null,"create",{value:customCreate});',
|
||||
'const change = Object.defineProperty.bind(null,Object); change.apply(null,["create",{value:customCreate}]);',
|
||||
'const change = Object.defineProperty.bind(null,Object); Reflect.apply(change,null,["create",{value:customCreate}]);',
|
||||
'Object.defineProperty.bind(null,Object,"create")({value:customCreate});',
|
||||
'const change = Object.defineProperty.bind(null,...args); change(Object,"create",{value:customCreate});',
|
||||
'const metadata = {}; Object.defineProperty.call(...args,metadata,"x",{value:1});',
|
||||
'const metadata = {}; Object.defineProperty.apply(...args,[metadata,"x",{value:1}]);',
|
||||
'const change = Function.prototype.call.bind(Object.defineProperty,null); change(Object,"create",{value:customCreate});',
|
||||
'const first = Function.prototype.call.bind(Object.defineProperty,null); const change = first.bind(customReceiver,Object,"create"); change({value:customCreate});',
|
||||
'const change = Function.prototype.apply.bind(Object.defineProperty,null); change([Object,"create",{value:customCreate}]);',
|
||||
'Function.prototype.call.call(Object.defineProperty,null,Object,"create",{value:customCreate});',
|
||||
'Function.prototype.apply.call(Object.defineProperty,null,[Object,"create",{value:customCreate}]);',
|
||||
'const uncurry = Function.prototype.call.bind(Function.prototype.call); uncurry(Object.defineProperty,null,Object,"create",{value:customCreate});',
|
||||
'const change = Function.prototype.bind.call(Object.defineProperty,null); change(Object,"create",{value:customCreate});',
|
||||
'const bind = Function.prototype.call.bind(Function.prototype.bind); const change = bind(Object.defineProperty,null); change(Object,"create",{value:customCreate});',
|
||||
'const change = Function.prototype.bind.apply(Object.defineProperty,[null,Object,"create"]); change({value:customCreate});',
|
||||
'const change = Reflect.apply(Function.prototype.bind,Object.defineProperty,[null,Object,"create"]); change({value:customCreate});',
|
||||
'const first = Object.defineProperty.bind(null,Object); const change = Function.prototype.bind.call(first,null,"create"); change({value:customCreate});',
|
||||
'Reflect.apply = Object.defineProperty; Reflect.apply(Object,"create",{value:customCreate});',
|
||||
'const apply = Reflect.apply; Reflect.apply = Object.defineProperty; Reflect.apply(Object,"create",{value:customCreate});',
|
||||
'const change = Reflect.set.bind(null,Object,"create"); change(customCreate);',
|
||||
'const change = Object.defineProperty.call; change.call(Object.defineProperty,null,Object,"create",{value:customCreate});',
|
||||
'const {apply:change} = Object.defineProperty; change.call(Object.defineProperty,null,[Object,"create",{value:customCreate}]);',
|
||||
'const change = Reflect.apply.call; change.call(Reflect.apply,null,Object.defineProperty,null,[Object,"create",{value:customCreate}]);',
|
||||
'Reflect.set({},"create",customCreate,Object);',
|
||||
'const metadata = {}; Reflect.set(metadata,"create",customCreate,Object);',
|
||||
'const change = Reflect.set.bind(null,{},"create",customCreate); change(Object);',
|
||||
'Reflect.apply(Reflect.set,null,[{},"create",customCreate,Object]);',
|
||||
'Reflect.set({},"create",customCreate,...receivers);',
|
||||
'Reflect.set({},"create",...valuesAndReceivers);',
|
||||
"Reflect.set({},...keysValuesAndReceivers);",
|
||||
'Reflect.set({},"create",customCreate,receiver);',
|
||||
'(0, Object.defineProperty)(Object,"create",{value:customCreate});',
|
||||
'const change = Object.defineProperty.bind(null,Object,"create"); (0, change)({value:customCreate});',
|
||||
'(0, Reflect.apply)(Object.defineProperty,null,[Object,"create",{value:customCreate}]);',
|
||||
'Reflect.apply((0,Function.prototype.call),Object.defineProperty,[null,Object,"create",{value:customCreate}]);',
|
||||
])("rejects intrinsic writes through a bound mutator: %s", (write) => {
|
||||
expect(
|
||||
analyzeJavaScriptStaticSource(
|
||||
`${write}\n${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP} ${WINDOW}`,
|
||||
).electron.browser_windows,
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'const change = Object.defineProperty.bind(null); change(metadata,"x",{value:1});',
|
||||
'const change = Object.defineProperty.bind(null,metadata,"x"); change({value:1});',
|
||||
'const first = Object.defineProperty.bind(null,metadata); const change = first.bind(null,"x"); change({value:1});',
|
||||
'const change = Function.prototype.call.bind(Object.defineProperty,null); change(metadata,"x",{value:1});',
|
||||
'const change = Function.prototype.apply.bind(Object.defineProperty,null); change([metadata,"x",{value:1}]);',
|
||||
'const change = Function.prototype.bind.call(Object.defineProperty,null,metadata,"x"); change({value:1});',
|
||||
'const bind = Function.prototype.call.bind(Function.prototype.bind); const change = bind(Object.defineProperty,null,metadata,"x"); change({value:1});',
|
||||
'const change = Function.prototype.bind.apply(Object.defineProperty,[null,metadata,"x"]); change({value:1});',
|
||||
'const change = Reflect.apply(Function.prototype.bind,Object.defineProperty,[null,metadata,"x"]); change({value:1});',
|
||||
'const apply = Reflect.apply; Reflect.apply = replacement; apply(Object.defineProperty,null,[metadata,"x",{value:1}]);',
|
||||
'const change = Object.defineProperty.bind(null,Object,"create");',
|
||||
'Object.defineProperty.call(null,metadata,"x",{value:1});',
|
||||
'Object.defineProperty.apply(null,[metadata,"x",{value:1}]);',
|
||||
'const change = Object.defineProperty.call; change.call(Object.defineProperty,null,metadata,"x",{value:1});',
|
||||
'const {apply:change} = Object.defineProperty; change.call(Object.defineProperty,null,[metadata,"x",{value:1}]);',
|
||||
'Reflect.set(metadata,"x",1,{});',
|
||||
'const receiver = {}; Reflect.set({},"x",1,receiver);',
|
||||
'(0, Object.defineProperty)(metadata,"x",{value:1});',
|
||||
])("keeps a fresh bound target or unused binding separate: %s", (write) => {
|
||||
expect(
|
||||
analyzeJavaScriptStaticSource(
|
||||
`const metadata = {}; ${write}\n${ROLLDOWN_MODULE_INTEROP}\n${IMPORT} ${WRAP} ${WINDOW}`,
|
||||
).electron.browser_windows,
|
||||
).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps unrelated exports after an aliased prebound key write", () => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`
|
||||
const electron = require("electron");
|
||||
const key = "Unrelated";
|
||||
const mutate = Object.defineProperty.bind(null, electron, key);
|
||||
mutate({value: custom});
|
||||
new electron.BrowserWindow({});
|
||||
`);
|
||||
expect(analysis.electron.browser_windows).toHaveLength(1);
|
||||
});
|
||||
@@ -77,7 +77,7 @@ describe("Electron API identity", () => {
|
||||
it("follows bundler namespace interop helpers without accepting other writes", () => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`
|
||||
var __toESM = (mod) => mod;
|
||||
var __importStar = (this && this.__importStar) || ((mod) => mod);
|
||||
var __importStar = (mod) => mod;
|
||||
let electron = require("electron");
|
||||
electron = __toESM(electron);
|
||||
new electron.BrowserWindow({ webPreferences: { preload: "./rolldown.js" } });
|
||||
@@ -120,4 +120,53 @@ describe("Electron API identity", () => {
|
||||
|
||||
expect(analysis.electron.browser_windows).toEqual([]);
|
||||
});
|
||||
|
||||
it("follows stable declaration aliases but not an assigned default parameter", () => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`
|
||||
const direct = require("electron");
|
||||
const constAlias = direct;
|
||||
new constAlias.BrowserWindow({webPreferences:{preload:"./const.js"}});
|
||||
|
||||
let letAlias = require("electron");
|
||||
new letAlias.BrowserWindow({webPreferences:{preload:"./let.js"}});
|
||||
|
||||
const { BrowserWindow } = require("electron");
|
||||
new BrowserWindow({webPreferences:{preload:"./destructured.js"}});
|
||||
|
||||
function withDefault(electron = require("./not-electron")) {
|
||||
if (flag) electron = require("electron");
|
||||
new electron.BrowserWindow({webPreferences:{preload:"./default.js"}});
|
||||
}
|
||||
`);
|
||||
|
||||
expect(
|
||||
analysis.electron.browser_windows.map(({ preload_path }) => preload_path),
|
||||
).toEqual(["./const.js", "./let.js", "./destructured.js"]);
|
||||
});
|
||||
|
||||
it("preserves one initializer across variable redeclarations without accepting writes", () => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`
|
||||
var electron;
|
||||
var electron = require("electron");
|
||||
var electron;
|
||||
new electron.BrowserWindow({webPreferences:{preload:"./redeclared.js"}});
|
||||
|
||||
var replaced;
|
||||
var replaced = require("electron");
|
||||
replaced = fake;
|
||||
new replaced.BrowserWindow({webPreferences:{preload:"./replaced.js"}});
|
||||
|
||||
var initializedTwice = require("electron");
|
||||
var initializedTwice = fake;
|
||||
new initializedTwice.BrowserWindow({});
|
||||
|
||||
var conditional;
|
||||
if (flag) { var conditional = require("electron"); }
|
||||
new conditional.BrowserWindow({});
|
||||
`);
|
||||
|
||||
expect(
|
||||
analysis.electron.browser_windows.map(({ preload_path }) => preload_path),
|
||||
).toEqual(["./redeclared.js"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -86,16 +86,20 @@ export const semanticObjectPatternKeys = (
|
||||
return key === null ? [] : [key];
|
||||
});
|
||||
|
||||
/** Visit member write targets in direct and destructuring assignment forms. */
|
||||
export function* semanticMemberWriteTargets(
|
||||
/** Visit binding and member leaves in direct and destructuring write targets. */
|
||||
export function* semanticWriteTargets(
|
||||
root: t.Node,
|
||||
): Generator<t.MemberExpression | t.OptionalMemberExpression> {
|
||||
): Generator<t.Identifier | t.MemberExpression | t.OptionalMemberExpression> {
|
||||
const pending = [root];
|
||||
while (pending.length > 0) {
|
||||
const next = pending.pop();
|
||||
if (next === undefined) break;
|
||||
const node = unwrapJavaScriptExpression(next).node;
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node))
|
||||
if (
|
||||
t.isIdentifier(node) ||
|
||||
t.isMemberExpression(node) ||
|
||||
t.isOptionalMemberExpression(node)
|
||||
)
|
||||
yield node;
|
||||
else if (t.isRestElement(node)) pending.push(node.argument);
|
||||
else if (t.isAssignmentPattern(node)) pending.push(node.left);
|
||||
|
||||
@@ -2,10 +2,9 @@ import * as t from "@babel/types";
|
||||
|
||||
import {
|
||||
semanticStaticPropertyKey,
|
||||
semanticMemberWriteTargets,
|
||||
semanticWriteTargets,
|
||||
unwrapJavaScriptExpression,
|
||||
} from "./javascriptAstValues.js";
|
||||
import { SemanticPropertyPathCoverage } from "./javascriptSemanticPropertyPaths.js";
|
||||
import { traverseJavaScriptAstSteps } from "./javascriptSemanticTraversal.js";
|
||||
|
||||
/** Match Electron's supported module entry points. */
|
||||
@@ -24,7 +23,7 @@ export const electronExportPath = (
|
||||
|
||||
/** Static identity recovery cannot establish the absence of Electron usage. */
|
||||
export const ELECTRON_IDENTITY_LIMITATION =
|
||||
"Electron API identity follows proven lexical module aliases, including results of namespace interop helpers (__toESM, __importStar, _interopRequireWildcard) recognized by name and a single program-scope function definition; helper bodies are not evaluated. Other reassigned bindings, dynamic selections, and visibly overwritten namespace members are unresolved; missing findings do not establish absence. Arbitrary call side effects and runtime registration are not evaluated.";
|
||||
"Electron API identity follows proven lexical module aliases and structurally verified module-namespace interop. Other reassignments, dynamic selections, and visibly overwritten namespace members are unresolved; missing findings do not establish absence. Arbitrary call side effects and runtime registration are not evaluated.";
|
||||
|
||||
/** Preserve exact property segments instead of flattening literal dotted keys. */
|
||||
export const electronMemberPath = (
|
||||
@@ -42,12 +41,96 @@ export const electronMemberPath = (
|
||||
return { root, members: members.toReversed() };
|
||||
};
|
||||
|
||||
/** Index visible writes through proven Electron aliases, without executing them. */
|
||||
export function* collectElectronMemberWritesSteps(
|
||||
/** A known intrinsic callable and its examined positional arguments. */
|
||||
export interface JavaScriptIntrinsicInvocation {
|
||||
readonly kind: "known" | "opaque";
|
||||
/** The original bound receiver; rebinding cannot replace it. */
|
||||
readonly receiver?: t.Node;
|
||||
readonly path: readonly string[];
|
||||
readonly arguments:
|
||||
| readonly t.CallExpression["arguments"][number][]
|
||||
| undefined;
|
||||
}
|
||||
|
||||
/** Index member and binding writes through caller-proven lexical identities. */
|
||||
export function* collectJavaScriptIdentityWritesSteps(
|
||||
program: t.Program,
|
||||
origin: (root: t.Node) => readonly string[] | undefined,
|
||||
): Generator<void, SemanticPropertyPathCoverage> {
|
||||
const writes = new SemanticPropertyPathCoverage();
|
||||
origin: (
|
||||
root: t.Node,
|
||||
kind: "binding" | "member" | "opaque-call",
|
||||
) => readonly string[] | undefined,
|
||||
intrinsicInvocation: (
|
||||
node: t.CallExpression | t.OptionalCallExpression,
|
||||
) => JavaScriptIntrinsicInvocation | undefined,
|
||||
staticString: (node: t.Node | undefined) => string | undefined,
|
||||
freshObject: (node: t.Node) => boolean,
|
||||
retain: (node: t.Node, path: readonly (string | null)[]) => void,
|
||||
): Generator<void> {
|
||||
const objectMutators = new Set([
|
||||
"defineProperty",
|
||||
"defineProperties",
|
||||
"assign",
|
||||
"setPrototypeOf",
|
||||
]);
|
||||
const reflectMutators = new Set([
|
||||
"set",
|
||||
"deleteProperty",
|
||||
"defineProperty",
|
||||
"setPrototypeOf",
|
||||
]);
|
||||
const keyedMutators = new Set(["set", "deleteProperty", "defineProperty"]);
|
||||
const retainCallEffects = (
|
||||
node: t.CallExpression | t.OptionalCallExpression,
|
||||
): void => {
|
||||
const invocation = intrinsicInvocation(node);
|
||||
if (invocation?.kind === "opaque") {
|
||||
const scope = origin(node, "opaque-call");
|
||||
if (scope !== undefined) retain(node, scope);
|
||||
return;
|
||||
}
|
||||
const callee = invocation?.path;
|
||||
const arguments_ = invocation?.arguments;
|
||||
const method = callee?.at(-1);
|
||||
const owner = callee?.length === 3 ? callee[1] : undefined;
|
||||
if (
|
||||
(owner === "Object" && objectMutators.has(method ?? "")) ||
|
||||
(owner === "Reflect" && reflectMutators.has(method ?? ""))
|
||||
) {
|
||||
// Reflect.set can write through its explicit receiver as well as
|
||||
// dispatching through its target. Both identities need examination.
|
||||
const targets =
|
||||
owner === "Reflect" &&
|
||||
method === "set" &&
|
||||
arguments_ !== undefined &&
|
||||
(arguments_.length >= 4 || arguments_.some(t.isSpreadElement))
|
||||
? [
|
||||
arguments_[0],
|
||||
arguments_.some(t.isSpreadElement) ? undefined : arguments_[3],
|
||||
]
|
||||
: [arguments_?.[0]];
|
||||
for (const target of targets) {
|
||||
// A known mutator with an opaque argument list can overwrite any
|
||||
// captured intrinsic. Do not turn an unexamined target into proof.
|
||||
if (target === undefined || t.isSpreadElement(target)) {
|
||||
const scope = origin(node, "opaque-call");
|
||||
if (scope !== undefined) retain(node, scope);
|
||||
}
|
||||
if (t.isNode(target) && !t.isSpreadElement(target)) {
|
||||
const { root, members } = electronMemberPath(target);
|
||||
const exported = origin(root, "member");
|
||||
if (exported !== undefined) {
|
||||
const key = keyedMutators.has(method ?? "")
|
||||
? [staticString(arguments_?.[1]) ?? null]
|
||||
: [];
|
||||
retain(node, [...exported, ...members, ...key]);
|
||||
} else if (!freshObject(target)) {
|
||||
const scope = origin(node, "opaque-call");
|
||||
if (scope !== undefined) retain(node, scope);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
yield* traverseJavaScriptAstSteps(program, {
|
||||
enter: (node) => {
|
||||
const target = t.isAssignmentExpression(node)
|
||||
@@ -60,12 +143,20 @@ export function* collectElectronMemberWritesSteps(
|
||||
? node.left
|
||||
: undefined;
|
||||
if (target === undefined) return;
|
||||
for (const member of semanticMemberWriteTargets(target)) {
|
||||
const { root, members } = electronMemberPath(member);
|
||||
const exported = origin(root);
|
||||
if (exported !== undefined) writes.retain([...exported, ...members]);
|
||||
for (const leaf of semanticWriteTargets(target)) {
|
||||
if (t.isIdentifier(leaf)) {
|
||||
const exported = origin(leaf, "binding");
|
||||
if (exported !== undefined) retain(node, exported);
|
||||
continue;
|
||||
}
|
||||
const { root, members } = electronMemberPath(leaf);
|
||||
const exported = origin(root, "member");
|
||||
if (exported !== undefined) retain(node, [...exported, ...members]);
|
||||
}
|
||||
},
|
||||
exit: (node) => {
|
||||
if (t.isCallExpression(node) || t.isOptionalCallExpression(node))
|
||||
retainCallEffects(node);
|
||||
},
|
||||
});
|
||||
return writes;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import type { JavaScriptIntrinsicInvocation } from "./javascriptElectronMemberWrites.js";
|
||||
import {
|
||||
semanticStaticPropertyKey,
|
||||
unwrapJavaScriptExpression,
|
||||
} from "./javascriptAstValues.js";
|
||||
|
||||
const arrayArguments = (array: t.Node | undefined) =>
|
||||
t.isArrayExpression(array) &&
|
||||
array.elements.every((element) => t.isExpression(element))
|
||||
? array.elements.filter((element): element is t.Expression =>
|
||||
t.isExpression(element),
|
||||
)
|
||||
: undefined;
|
||||
|
||||
const invocationArguments = (
|
||||
method: "call" | "apply",
|
||||
arguments_: JavaScriptIntrinsicInvocation["arguments"],
|
||||
) =>
|
||||
t.isSpreadElement(arguments_?.[0])
|
||||
? undefined
|
||||
: method === "apply"
|
||||
? arrayArguments(arguments_?.[1])
|
||||
: arguments_?.slice(1);
|
||||
|
||||
/**
|
||||
* Normalize known invocation syntax once, retaining bound argument prefixes.
|
||||
* Binding a function alone is not a write; only its eventual call is examined.
|
||||
*/
|
||||
export const resolveJavaScriptIntrinsicInvocation = (
|
||||
node: t.CallExpression | t.OptionalCallExpression,
|
||||
intrinsicPath: (node: t.Node) => readonly string[] | undefined,
|
||||
boundIntrinsic: (node: t.Node) => JavaScriptIntrinsicInvocation | undefined,
|
||||
intrinsicReadChanged: (node: t.Node, path: readonly string[]) => boolean,
|
||||
): JavaScriptIntrinsicInvocation | undefined => {
|
||||
const visited = new Set<t.Node>();
|
||||
let callee: t.Node = node.callee;
|
||||
let arguments_: JavaScriptIntrinsicInvocation["arguments"] = node.arguments;
|
||||
let receiver: t.Node | undefined;
|
||||
let explicitReceiver = false;
|
||||
for (;;) {
|
||||
callee = unwrapJavaScriptExpression(callee).node;
|
||||
if (t.isSequenceExpression(callee)) {
|
||||
const finalExpression = callee.expressions.at(-1);
|
||||
if (finalExpression === undefined) return undefined;
|
||||
// Comma yields a value, not a member reference. An outer invocation
|
||||
// can still supply an explicit receiver for that value.
|
||||
explicitReceiver = true;
|
||||
callee = finalExpression;
|
||||
continue;
|
||||
}
|
||||
if (visited.has(callee)) return undefined;
|
||||
visited.add(callee);
|
||||
let path = intrinsicPath(callee);
|
||||
if (path !== undefined && intrinsicReadChanged(callee, path))
|
||||
return { kind: "opaque", path, arguments: undefined };
|
||||
if (path === undefined) {
|
||||
if (
|
||||
t.isMemberExpression(callee) ||
|
||||
t.isOptionalMemberExpression(callee)
|
||||
) {
|
||||
const method = semanticStaticPropertyKey(
|
||||
callee.property,
|
||||
callee.computed,
|
||||
);
|
||||
if (method === "call" || method === "apply") {
|
||||
const bound = boundIntrinsic(callee.object);
|
||||
if (
|
||||
bound !== undefined &&
|
||||
intrinsicReadChanged(callee, [...bound.path, method])
|
||||
)
|
||||
return { kind: "opaque", path: bound.path, arguments: undefined };
|
||||
receiver = arguments_?.[0];
|
||||
explicitReceiver = true;
|
||||
callee = callee.object;
|
||||
arguments_ = invocationArguments(method, arguments_);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const bound = boundIntrinsic(callee);
|
||||
if (bound === undefined) return undefined;
|
||||
if (bound.kind === "opaque") return bound;
|
||||
path = bound.path;
|
||||
receiver = bound.receiver;
|
||||
explicitReceiver = true;
|
||||
arguments_ =
|
||||
bound.arguments === undefined
|
||||
? undefined
|
||||
: [...bound.arguments, ...(arguments_ ?? [])];
|
||||
}
|
||||
const method = path.length > 3 ? path.at(-1) : undefined;
|
||||
if (method === "call" || method === "apply") {
|
||||
// These properties hold generic function values. Their receiver selects
|
||||
// the callable; property-chain depth does not consume more arguments.
|
||||
const callable: t.Node | undefined = explicitReceiver
|
||||
? receiver
|
||||
: t.isMemberExpression(callee) || t.isOptionalMemberExpression(callee)
|
||||
? callee.object
|
||||
: undefined;
|
||||
if (!t.isExpression(callable)) return undefined;
|
||||
callee = callable;
|
||||
receiver = arguments_?.[0];
|
||||
explicitReceiver = true;
|
||||
arguments_ = invocationArguments(method, arguments_);
|
||||
continue;
|
||||
}
|
||||
if (path.join(".") === "intrinsic.Reflect.apply") {
|
||||
const callable = arguments_?.[0];
|
||||
if (!t.isExpression(callable)) return undefined;
|
||||
callee = callable;
|
||||
receiver = arguments_?.[1];
|
||||
explicitReceiver = true;
|
||||
arguments_ = arrayArguments(arguments_?.[2]);
|
||||
continue;
|
||||
}
|
||||
return {
|
||||
kind: "known",
|
||||
path,
|
||||
arguments: arguments_,
|
||||
...(receiver === undefined ? {} : { receiver }),
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
// Rolldown runtime from the public T3 Code nightly 20261011.2967 main.cjs.
|
||||
// The input is inert source: none of these helpers or Electron APIs is executed.
|
||||
export const ROLLDOWN_MODULE_INTEROP = `
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
||||
key = keys[i];
|
||||
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
||||
get: ((k) => from[k]).bind(null, key),
|
||||
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
||||
});
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
||||
value: mod,
|
||||
enumerable: true
|
||||
}) : target, mod));
|
||||
`;
|
||||
@@ -0,0 +1,826 @@
|
||||
import { parseExpression } from "@babel/parser";
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import type { JavaScriptModuleOrigin } from "./javascriptSemanticIr.js";
|
||||
import {
|
||||
isUnshadowedGlobal,
|
||||
resolveSemanticBindingState,
|
||||
semanticScopeId,
|
||||
semanticStableInitializer,
|
||||
type JavaScriptSemanticAnalysisState,
|
||||
type JavaScriptSemanticBindingState,
|
||||
} from "./javascriptSemanticState.js";
|
||||
import { semanticRequireOrigin } from "./javascriptSemanticRequireOrigin.js";
|
||||
import {
|
||||
childNodes,
|
||||
javaScriptAstChildKeys,
|
||||
} from "./javascriptSemanticTraversal.js";
|
||||
import {
|
||||
electronMemberPath,
|
||||
type JavaScriptIntrinsicInvocation,
|
||||
} from "./javascriptElectronMemberWrites.js";
|
||||
import { resolveJavaScriptIntrinsicInvocation } from "./javascriptIntrinsicInvocation.js";
|
||||
import { semanticPropertyPathKeyMatches } from "./javascriptSemanticPropertyPaths.js";
|
||||
import {
|
||||
readExactJavaScriptLiteral,
|
||||
unwrapJavaScriptExpression,
|
||||
} from "./javascriptAstValues.js";
|
||||
|
||||
// Match the complete Rolldown runtime operations, including its live getters.
|
||||
// Names and formatting are irrelevant; lexical roles, operators and keys are not.
|
||||
const TO_ESM = parseExpression(`(mod, isNodeMode, target) => (
|
||||
target = mod != null ? __create(__getProtoOf(mod)) : {},
|
||||
__copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default")
|
||||
? __defProp(target, "default", {value: mod, enumerable: true}) : target, mod)
|
||||
)`);
|
||||
const COPY_PROPS = parseExpression(`(to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function")
|
||||
for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
||||
key = keys[i];
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, {
|
||||
get: ((k) => from[k]).bind(null, key),
|
||||
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
||||
});
|
||||
}
|
||||
return to;
|
||||
}`);
|
||||
const INTRINSICS: Readonly<Record<string, readonly string[]>> = {
|
||||
__create: ["Object", "create"],
|
||||
__getProtoOf: ["Object", "getPrototypeOf"],
|
||||
__defProp: ["Object", "defineProperty"],
|
||||
__getOwnPropNames: ["Object", "getOwnPropertyNames"],
|
||||
__getOwnPropDesc: ["Object", "getOwnPropertyDescriptor"],
|
||||
__hasOwnProp: ["Object", "prototype", "hasOwnProperty"],
|
||||
};
|
||||
|
||||
interface IntrinsicDependency {
|
||||
readonly path: readonly string[];
|
||||
readonly capturedAt?: t.Node;
|
||||
}
|
||||
|
||||
interface InteropOrigin {
|
||||
readonly origin: JavaScriptModuleOrigin;
|
||||
readonly dependencies: readonly IntrinsicDependency[];
|
||||
readonly defaultIsModule: boolean;
|
||||
}
|
||||
|
||||
interface InteropHelper {
|
||||
readonly dependencies: readonly IntrinsicDependency[];
|
||||
readonly readyAfter: number;
|
||||
readonly identity: boolean;
|
||||
}
|
||||
|
||||
const intrinsicWriteCovers = (
|
||||
written: readonly (string | null)[],
|
||||
read: readonly string[],
|
||||
): boolean =>
|
||||
written.length <= read.length &&
|
||||
written.every((key, index) => {
|
||||
const name = read[index];
|
||||
return name !== undefined && semanticPropertyPathKeyMatches(key, name);
|
||||
});
|
||||
|
||||
/** Prove one inert namespace conversion without relaxing general assignment semantics. */
|
||||
export const createSemanticModuleInterop = (
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
) => {
|
||||
const helpers = new Map<string, InteropHelper | null>();
|
||||
const origins = new Map<string, InteropOrigin>();
|
||||
const calls = new WeakMap<t.Node, InteropOrigin>();
|
||||
const intrinsicBindings = new Map<string, readonly string[] | null>();
|
||||
const writes: {
|
||||
readonly scope: string;
|
||||
readonly offset: number;
|
||||
readonly path: readonly (string | null)[];
|
||||
}[] = [];
|
||||
const invalidatedBindings = new Map<string, boolean>();
|
||||
const invalidatedCalls = new WeakMap<t.Node, boolean>();
|
||||
const opaqueMutationPath = (node: t.Node): readonly string[] => {
|
||||
let current: t.Node | undefined = node;
|
||||
while (current !== undefined) {
|
||||
if (t.isFunction(current))
|
||||
return ["opaque-intrinsic", semanticScopeId("function", current)];
|
||||
current = state.parentsByNode.get(current);
|
||||
}
|
||||
return ["intrinsic"];
|
||||
};
|
||||
|
||||
const intrinsicPath = (node: t.Node): readonly string[] | undefined => {
|
||||
let current = node;
|
||||
const visited = new Set<string>();
|
||||
const pending: { id: string; suffixLength: number }[] = [];
|
||||
let suffix: readonly string[] = [];
|
||||
const finish = (
|
||||
path: readonly string[] | undefined,
|
||||
): readonly string[] | undefined => {
|
||||
for (const binding of pending)
|
||||
intrinsicBindings.set(
|
||||
binding.id,
|
||||
path === undefined
|
||||
? null
|
||||
: path.slice(0, path.length - binding.suffixLength),
|
||||
);
|
||||
return path;
|
||||
};
|
||||
for (;;) {
|
||||
const { root, members } = electronMemberPath(current);
|
||||
if (members.some((member) => member === null)) return finish(undefined);
|
||||
suffix = [...(members as readonly string[]), ...suffix];
|
||||
if (t.isSequenceExpression(root)) {
|
||||
const value = root.expressions.at(-1);
|
||||
if (value === undefined) return finish(undefined);
|
||||
current = value;
|
||||
continue;
|
||||
}
|
||||
for (const global of ["Object", "Function", "Reflect"])
|
||||
if (isUnshadowedGlobal(root, state, global))
|
||||
return finish(["intrinsic", global, ...suffix]);
|
||||
for (const global of ["globalThis", "global", "window", "self"])
|
||||
if (isUnshadowedGlobal(root, state, global))
|
||||
return finish(["intrinsic", ...suffix]);
|
||||
if (!t.isIdentifier(root)) return finish(undefined);
|
||||
const binding = resolveSemanticBindingState(state, root, root.name);
|
||||
const cached =
|
||||
binding === undefined
|
||||
? undefined
|
||||
: intrinsicBindings.get(binding.bindingId);
|
||||
if (cached !== undefined)
|
||||
return finish(cached === null ? undefined : [...cached, ...suffix]);
|
||||
const initializer = semanticStableInitializer(binding, state);
|
||||
if (
|
||||
binding === undefined ||
|
||||
initializer === undefined ||
|
||||
initializer.projection.some((segment) => segment === null) ||
|
||||
visited.has(binding.bindingId)
|
||||
)
|
||||
return finish(undefined);
|
||||
visited.add(binding.bindingId);
|
||||
pending.push({ id: binding.bindingId, suffixLength: suffix.length });
|
||||
suffix = [...initializer.projection.map(String), ...suffix];
|
||||
current = initializer.node;
|
||||
}
|
||||
};
|
||||
|
||||
// A nominal alias path is sufficient for conservative mutation lookup, but
|
||||
// helper proof also needs each read to follow initialization. An alias copy
|
||||
// retains the earlier function capture; a member read captures it anew.
|
||||
const capturedIntrinsic = (node: t.Node): IntrinsicDependency | undefined => {
|
||||
const path = intrinsicPath(node);
|
||||
if (path === undefined) return undefined;
|
||||
const visited = new Set<string>();
|
||||
let current = node;
|
||||
let capturedAt = node;
|
||||
let suffixLength = 0;
|
||||
for (;;) {
|
||||
current = unwrapJavaScriptExpression(current).node;
|
||||
if (suffixLength === 0)
|
||||
capturedAt =
|
||||
t.isMemberExpression(current) || t.isOptionalMemberExpression(current)
|
||||
? current.property
|
||||
: current;
|
||||
const { root, members } = electronMemberPath(current);
|
||||
suffixLength += members.length;
|
||||
if (t.isSequenceExpression(root)) {
|
||||
const value = root.expressions.at(-1);
|
||||
if (value === undefined) return undefined;
|
||||
current = value;
|
||||
continue;
|
||||
}
|
||||
if (!t.isIdentifier(root)) return undefined;
|
||||
const binding = resolveSemanticBindingState(state, root, root.name);
|
||||
if (binding === undefined) return { path, capturedAt };
|
||||
const initializer = semanticStableInitializer(binding, state);
|
||||
if (
|
||||
initializer === undefined ||
|
||||
(initializer.node.end ?? Infinity) >= (root.start ?? -1) ||
|
||||
visited.has(binding.bindingId)
|
||||
)
|
||||
return undefined;
|
||||
visited.add(binding.bindingId);
|
||||
if (suffixLength === 0) capturedAt = initializer.node;
|
||||
suffixLength += initializer.projection.length;
|
||||
current = initializer.node;
|
||||
}
|
||||
};
|
||||
|
||||
const staticString = (node: t.Node | undefined): string | undefined => {
|
||||
if (node === undefined) return undefined;
|
||||
const visited = new Set<string>();
|
||||
let current = node;
|
||||
for (;;) {
|
||||
const literal = readExactJavaScriptLiteral(current);
|
||||
if (literal.found)
|
||||
return typeof literal.value === "string" ? literal.value : undefined;
|
||||
const expression = unwrapJavaScriptExpression(current).node;
|
||||
if (!t.isIdentifier(expression)) return undefined;
|
||||
const binding = resolveSemanticBindingState(
|
||||
state,
|
||||
expression,
|
||||
expression.name,
|
||||
);
|
||||
const initializer = semanticStableInitializer(binding, state);
|
||||
if (
|
||||
binding === undefined ||
|
||||
initializer === undefined ||
|
||||
initializer.projection.length !== 0 ||
|
||||
(initializer.node.end ?? Infinity) >= (expression.start ?? -1) ||
|
||||
visited.has(binding.bindingId)
|
||||
)
|
||||
return undefined;
|
||||
visited.add(binding.bindingId);
|
||||
current = initializer.node;
|
||||
}
|
||||
};
|
||||
|
||||
const intrinsicReadChanged = (
|
||||
node: t.Node,
|
||||
path: readonly string[],
|
||||
): boolean => {
|
||||
let current = unwrapJavaScriptExpression(node).node;
|
||||
let currentPath = path;
|
||||
for (;;) {
|
||||
const method = currentPath.at(-1);
|
||||
const invocationMethod =
|
||||
method === "bind" || method === "call" || method === "apply";
|
||||
if (
|
||||
invocationMethod &&
|
||||
(t.isMemberExpression(current) || t.isOptionalMemberExpression(current))
|
||||
) {
|
||||
// Reading an invocation member does not recapture the stored function.
|
||||
// Check member writes now, then check its base at the earlier capture.
|
||||
const scope = opaqueMutationPath(current).join(".");
|
||||
const offset = current.property.start ?? -1;
|
||||
if (
|
||||
writes.some(
|
||||
(write) =>
|
||||
(write.scope === scope || write.scope === "intrinsic") &&
|
||||
write.offset < offset &&
|
||||
((write.path.length >= currentPath.length &&
|
||||
intrinsicWriteCovers(write.path, currentPath)) ||
|
||||
intrinsicWriteCovers(write.path, [
|
||||
"intrinsic",
|
||||
"Function",
|
||||
"prototype",
|
||||
method,
|
||||
])),
|
||||
)
|
||||
)
|
||||
return true;
|
||||
current = unwrapJavaScriptExpression(current.object).node;
|
||||
currentPath = currentPath.slice(0, -1);
|
||||
continue;
|
||||
}
|
||||
const capture = capturedIntrinsic(current)?.capturedAt ?? current;
|
||||
const scope = opaqueMutationPath(capture).join(".");
|
||||
return writes.some(
|
||||
(write) =>
|
||||
(write.scope === scope || write.scope === "intrinsic") &&
|
||||
write.offset < (capture.start ?? -1) &&
|
||||
(intrinsicWriteCovers(write.path, currentPath) ||
|
||||
(invocationMethod &&
|
||||
intrinsicWriteCovers(write.path, [
|
||||
"intrinsic",
|
||||
"Function",
|
||||
"prototype",
|
||||
method,
|
||||
]))),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const resolveBoundIntrinsic = (
|
||||
node: t.Node,
|
||||
): JavaScriptIntrinsicInvocation | undefined => {
|
||||
const visited = new Set<string>();
|
||||
const argumentGroups: t.CallExpression["arguments"][] = [];
|
||||
const bindReads: t.Node[] = [];
|
||||
let opaqueArguments = false;
|
||||
let receiver: t.Node | undefined;
|
||||
let current = node;
|
||||
for (;;) {
|
||||
current = unwrapJavaScriptExpression(current).node;
|
||||
if (t.isIdentifier(current)) {
|
||||
const binding = resolveSemanticBindingState(
|
||||
state,
|
||||
current,
|
||||
current.name,
|
||||
);
|
||||
const initializer = semanticStableInitializer(binding, state);
|
||||
if (
|
||||
binding === undefined ||
|
||||
initializer === undefined ||
|
||||
initializer.projection.length !== 0 ||
|
||||
(initializer.node.end ?? Infinity) >= (current.start ?? -1) ||
|
||||
visited.has(binding.bindingId)
|
||||
)
|
||||
return undefined;
|
||||
visited.add(binding.bindingId);
|
||||
current = initializer.node;
|
||||
continue;
|
||||
}
|
||||
if (!t.isCallExpression(current)) return undefined;
|
||||
const { root, members } = electronMemberPath(current.callee);
|
||||
let bindTarget = root;
|
||||
let bindingArguments: JavaScriptIntrinsicInvocation["arguments"] =
|
||||
current.arguments;
|
||||
let captured = capturedIntrinsic(current.callee);
|
||||
let terminal = captured?.path.at(-1) === "bind";
|
||||
let path: readonly string[] | undefined = captured?.path.slice(0, -1);
|
||||
if (members.at(-1) === "bind") {
|
||||
// A direct .bind may continue a bound callable, without discarding members.
|
||||
if (!terminal && members.length !== 1) return undefined;
|
||||
bindReads.push(current.callee);
|
||||
} else {
|
||||
// Reuse the invocation owner for generic call/apply/Reflect.apply of bind.
|
||||
const invocation = resolveJavaScriptIntrinsicInvocation(
|
||||
current,
|
||||
intrinsicPath,
|
||||
boundIntrinsic,
|
||||
intrinsicReadChanged,
|
||||
);
|
||||
if (
|
||||
invocation?.kind !== "known" ||
|
||||
invocation.path.join(".") !== "intrinsic.Function.prototype.bind" ||
|
||||
invocation.receiver === undefined
|
||||
)
|
||||
return undefined;
|
||||
bindTarget = invocation.receiver;
|
||||
bindingArguments = invocation.arguments;
|
||||
captured = capturedIntrinsic(bindTarget);
|
||||
terminal = captured !== undefined;
|
||||
path = captured?.path;
|
||||
opaqueArguments ||=
|
||||
path !== undefined && intrinsicReadChanged(bindTarget, path);
|
||||
}
|
||||
receiver = bindingArguments?.[0];
|
||||
const ownArguments = bindingArguments?.slice(1) ?? [];
|
||||
opaqueArguments ||=
|
||||
bindingArguments === undefined || t.isSpreadElement(receiver);
|
||||
opaqueArguments ||= ownArguments.some((argument) =>
|
||||
t.isSpreadElement(argument),
|
||||
);
|
||||
argumentGroups.push(ownArguments);
|
||||
if (!terminal || path === undefined) {
|
||||
current = bindTarget;
|
||||
continue;
|
||||
}
|
||||
const boundPath = [...path, "bind"];
|
||||
opaqueArguments ||= bindReads.some((capture) =>
|
||||
intrinsicReadChanged(capture, boundPath),
|
||||
);
|
||||
return {
|
||||
kind: opaqueArguments ? "opaque" : "known",
|
||||
path,
|
||||
...(receiver === undefined ? {} : { receiver }),
|
||||
// Rebinding appends arguments to the earlier bound argument list.
|
||||
arguments: opaqueArguments
|
||||
? undefined
|
||||
: argumentGroups.toReversed().flat(),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const activeBoundValues = new WeakSet<t.Node>();
|
||||
const boundIntrinsic = (
|
||||
node: t.Node,
|
||||
): JavaScriptIntrinsicInvocation | undefined => {
|
||||
if (activeBoundValues.has(node)) return undefined;
|
||||
activeBoundValues.add(node);
|
||||
try {
|
||||
return resolveBoundIntrinsic(node);
|
||||
} finally {
|
||||
activeBoundValues.delete(node);
|
||||
}
|
||||
};
|
||||
|
||||
const isFreshObject = (node: t.Node): boolean => {
|
||||
const visited = new Set<string>();
|
||||
let current = node;
|
||||
for (;;) {
|
||||
current = unwrapJavaScriptExpression(current).node;
|
||||
if (
|
||||
t.isObjectExpression(current) ||
|
||||
t.isArrayExpression(current) ||
|
||||
t.isFunction(current) ||
|
||||
(t.isClass(current) && !current.decorators?.length) ||
|
||||
t.isRegExpLiteral(current)
|
||||
)
|
||||
return true;
|
||||
if (!t.isIdentifier(current)) return false;
|
||||
const binding = resolveSemanticBindingState(state, current, current.name);
|
||||
const initializer = unprojectedInitializer(binding, state);
|
||||
if (
|
||||
binding === undefined ||
|
||||
initializer === undefined ||
|
||||
(!t.isFunctionDeclaration(initializer) &&
|
||||
(initializer.end ?? Infinity) >= (current.start ?? -1)) ||
|
||||
visited.has(binding.bindingId)
|
||||
)
|
||||
return false;
|
||||
visited.add(binding.bindingId);
|
||||
current = initializer;
|
||||
}
|
||||
};
|
||||
|
||||
const helperProof = (
|
||||
binding: JavaScriptSemanticBindingState,
|
||||
): InteropHelper | undefined => {
|
||||
const cached = helpers.get(binding.bindingId);
|
||||
if (cached !== undefined) return cached ?? undefined;
|
||||
helpers.set(binding.bindingId, null);
|
||||
if (state.scopesById.get(binding.scopeId)?.kind !== "program")
|
||||
return undefined;
|
||||
const wrapper = unprojectedInitializer(binding, state);
|
||||
if (wrapper === undefined) return undefined;
|
||||
if (identityFunction(wrapper, state)) {
|
||||
const proof = {
|
||||
dependencies: [],
|
||||
readyAfter: t.isFunctionDeclaration(wrapper)
|
||||
? -1
|
||||
: (wrapper.end ?? Infinity),
|
||||
identity: true,
|
||||
};
|
||||
helpers.set(binding.bindingId, proof);
|
||||
return proof;
|
||||
}
|
||||
const wrapperRoles = canonicalRoles(wrapper, TO_ESM, state);
|
||||
const copyBinding = wrapperRoles?.get("__copyProps");
|
||||
const copy = unprojectedInitializer(copyBinding, state);
|
||||
const copyRoles =
|
||||
copy === undefined ? undefined : canonicalRoles(copy, COPY_PROPS, state);
|
||||
if (
|
||||
wrapperRoles === undefined ||
|
||||
copyRoles === undefined ||
|
||||
copy === undefined
|
||||
)
|
||||
return undefined;
|
||||
const dependencies: IntrinsicDependency[] = [];
|
||||
let readyAfter = Math.max(wrapper.end ?? Infinity, copy.end ?? Infinity);
|
||||
for (const roles of [wrapperRoles, copyRoles])
|
||||
for (const [role, dependency] of roles) {
|
||||
const expected = INTRINSICS[role];
|
||||
if (expected === undefined) continue;
|
||||
const initializer = unprojectedInitializer(dependency, state);
|
||||
const captured =
|
||||
initializer === undefined
|
||||
? undefined
|
||||
: capturedIntrinsic(initializer);
|
||||
if (
|
||||
initializer === undefined ||
|
||||
captured === undefined ||
|
||||
JSON.stringify(captured.path) !==
|
||||
JSON.stringify(["intrinsic", ...expected])
|
||||
)
|
||||
return undefined;
|
||||
readyAfter = Math.max(readyAfter, initializer.end ?? Infinity);
|
||||
dependencies.push(captured);
|
||||
if (role === "__hasOwnProp")
|
||||
dependencies.push({ path: [...captured.path, "call"] });
|
||||
}
|
||||
dependencies.push(
|
||||
{ path: ["intrinsic", "Function", "prototype", "bind"] },
|
||||
{ path: ["intrinsic", "Function", "prototype", "call"] },
|
||||
);
|
||||
const proof = {
|
||||
dependencies,
|
||||
identity: false,
|
||||
readyAfter,
|
||||
};
|
||||
helpers.set(binding.bindingId, proof);
|
||||
return proof;
|
||||
};
|
||||
|
||||
const provenCall = (node: t.Node) => {
|
||||
if (!t.isCallExpression(node) || !t.isIdentifier(node.callee))
|
||||
return undefined;
|
||||
const helper = resolveSemanticBindingState(
|
||||
state,
|
||||
node.callee,
|
||||
node.callee.name,
|
||||
);
|
||||
const proof = helper === undefined ? undefined : helperProof(helper);
|
||||
const input = node.arguments[0];
|
||||
const mode = node.arguments[1];
|
||||
const literalMode =
|
||||
mode === undefined
|
||||
? { found: true, value: false }
|
||||
: t.isExpression(mode)
|
||||
? readExactJavaScriptLiteral(mode)
|
||||
: { found: false };
|
||||
if (
|
||||
proof === undefined ||
|
||||
proof.readyAfter >= (node.start ?? -1) ||
|
||||
!t.isExpression(input) ||
|
||||
node.arguments.length > 2 ||
|
||||
!literalMode.found
|
||||
)
|
||||
return undefined;
|
||||
return {
|
||||
input,
|
||||
// A truthy node mode forces the module-valued default. Other modes
|
||||
// preserve named exports without proving the source's default property.
|
||||
defaultIsModule: !proof.identity && Boolean(literalMode.value),
|
||||
dependencies: proof.dependencies.map((dependency) => ({
|
||||
...dependency,
|
||||
capturedAt: dependency.capturedAt ?? node,
|
||||
})),
|
||||
};
|
||||
};
|
||||
|
||||
const callOrigin = (node: t.Node): InteropOrigin | undefined => {
|
||||
const cached = calls.get(node);
|
||||
if (cached !== undefined) return cached;
|
||||
const { root, members } = electronMemberPath(node);
|
||||
if (!members.every((member): member is string => member !== null))
|
||||
return undefined;
|
||||
const converted = provenCall(root);
|
||||
const required =
|
||||
converted === undefined
|
||||
? undefined
|
||||
: semanticRequireOrigin(converted.input, state)?.origin;
|
||||
if (
|
||||
converted === undefined ||
|
||||
required === undefined ||
|
||||
required.importedPath.length !== 0 ||
|
||||
(members[0] === "default" && !converted.defaultIsModule)
|
||||
)
|
||||
return undefined;
|
||||
const result = {
|
||||
origin: { ...required, importedPath: members },
|
||||
dependencies: converted.dependencies,
|
||||
defaultIsModule: converted.defaultIsModule,
|
||||
};
|
||||
calls.set(node, result);
|
||||
return result;
|
||||
};
|
||||
|
||||
const origin = (
|
||||
binding: JavaScriptSemanticBindingState,
|
||||
): InteropOrigin | undefined => {
|
||||
const single = semanticStableInitializer(binding, state);
|
||||
if (single !== undefined) {
|
||||
if (
|
||||
!single.projection.every(
|
||||
(key): key is string => typeof key === "string",
|
||||
)
|
||||
)
|
||||
return undefined;
|
||||
const converted = callOrigin(single.node);
|
||||
if (
|
||||
converted?.origin.importedPath.length === 0 &&
|
||||
single.projection[0] === "default" &&
|
||||
!converted.defaultIsModule
|
||||
)
|
||||
return undefined;
|
||||
const result =
|
||||
converted === undefined
|
||||
? undefined
|
||||
: {
|
||||
...converted,
|
||||
origin: {
|
||||
...converted.origin,
|
||||
importedPath: [
|
||||
...converted.origin.importedPath,
|
||||
...single.projection,
|
||||
],
|
||||
},
|
||||
};
|
||||
if (result !== undefined) origins.set(binding.bindingId, result);
|
||||
return result;
|
||||
}
|
||||
const [initial, converted] = binding.initializers;
|
||||
if (
|
||||
binding.definitions.length !== 2 ||
|
||||
binding.definitions[0]?.kind !== "variable" ||
|
||||
binding.definitions[1]?.kind !== "assignment" ||
|
||||
binding.initializers.length !== 2 ||
|
||||
initial === undefined ||
|
||||
converted === undefined ||
|
||||
initial.projection.length !== 0 ||
|
||||
converted.projection.length !== 0 ||
|
||||
state.conditionalInitializers.has(initial.node)
|
||||
)
|
||||
return undefined;
|
||||
const call = converted.node;
|
||||
const assignment = state.parentsByNode.get(call);
|
||||
const statement =
|
||||
assignment === undefined
|
||||
? undefined
|
||||
: state.parentsByNode.get(assignment);
|
||||
const declaration = state.parentsByNode.get(initial.node);
|
||||
const declarationStatement =
|
||||
declaration === undefined
|
||||
? undefined
|
||||
: state.parentsByNode.get(declaration);
|
||||
if (
|
||||
!t.isCallExpression(call) ||
|
||||
!t.isIdentifier(call.callee) ||
|
||||
!t.isAssignmentExpression(assignment, { operator: "=" }) ||
|
||||
assignment.right !== call ||
|
||||
!t.isIdentifier(assignment.left, { name: binding.name }) ||
|
||||
!t.isExpressionStatement(statement) ||
|
||||
!t.isVariableDeclarator(declaration) ||
|
||||
!t.isVariableDeclaration(declarationStatement) ||
|
||||
state.parentsByNode.get(statement) !==
|
||||
state.parentsByNode.get(declarationStatement) ||
|
||||
(initial.node.start ?? Infinity) >= (call.start ?? -1)
|
||||
)
|
||||
return undefined;
|
||||
const convertedCall = provenCall(call);
|
||||
const input = convertedCall?.input;
|
||||
if (
|
||||
!t.isIdentifier(input) ||
|
||||
resolveSemanticBindingState(state, input, input.name) !== binding
|
||||
)
|
||||
return undefined;
|
||||
const required = semanticRequireOrigin(initial.node, state)?.origin;
|
||||
if (required === undefined || required.importedPath.length !== 0)
|
||||
return undefined;
|
||||
if (convertedCall === undefined) return undefined;
|
||||
const result = {
|
||||
origin: required,
|
||||
dependencies: convertedCall.dependencies,
|
||||
defaultIsModule: convertedCall.defaultIsModule,
|
||||
};
|
||||
origins.set(binding.bindingId, result);
|
||||
return result;
|
||||
};
|
||||
const invalidatedOrigin = (record: InteropOrigin | undefined): boolean =>
|
||||
record?.dependencies.some(({ path, capturedAt }) => {
|
||||
if (capturedAt === undefined) return true;
|
||||
const scope = opaqueMutationPath(capturedAt).join(".");
|
||||
// Captured function values survive later replacement of global
|
||||
// properties. Other callable bodies are not execution evidence.
|
||||
return writes.some(
|
||||
(write) =>
|
||||
(write.scope === scope || write.scope === "intrinsic") &&
|
||||
write.offset < (capturedAt.start ?? -1) &&
|
||||
intrinsicWriteCovers(write.path, path),
|
||||
);
|
||||
}) ?? false;
|
||||
return {
|
||||
origin,
|
||||
callOrigin,
|
||||
intrinsicPath,
|
||||
intrinsicInvocation: (node: t.CallExpression | t.OptionalCallExpression) =>
|
||||
resolveJavaScriptIntrinsicInvocation(
|
||||
node,
|
||||
intrinsicPath,
|
||||
boundIntrinsic,
|
||||
intrinsicReadChanged,
|
||||
),
|
||||
boundIntrinsic,
|
||||
staticString,
|
||||
isFreshObject,
|
||||
opaqueMutationPath,
|
||||
retainWrite: (node: t.Node, path: readonly (string | null)[]) => {
|
||||
writes.push({
|
||||
scope: opaqueMutationPath(node).join("."),
|
||||
offset: node.start ?? Infinity,
|
||||
path: path[0] === "opaque-intrinsic" ? ["intrinsic"] : path,
|
||||
});
|
||||
},
|
||||
invalidated: (binding: JavaScriptSemanticBindingState): boolean => {
|
||||
const cached = invalidatedBindings.get(binding.bindingId);
|
||||
if (cached !== undefined) return cached;
|
||||
const result = invalidatedOrigin(origins.get(binding.bindingId));
|
||||
invalidatedBindings.set(binding.bindingId, result);
|
||||
return result;
|
||||
},
|
||||
invalidatedCall: (node: t.Node): boolean => {
|
||||
const cached = invalidatedCalls.get(node);
|
||||
if (cached !== undefined) return cached;
|
||||
const result = invalidatedOrigin(calls.get(node));
|
||||
invalidatedCalls.set(node, result);
|
||||
return result;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const identityFunction = (
|
||||
node: t.Node,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): boolean => {
|
||||
if (
|
||||
!t.isFunction(node) ||
|
||||
node.async ||
|
||||
node.generator ||
|
||||
node.params.length !== 1
|
||||
)
|
||||
return false;
|
||||
const parameter = node.params[0];
|
||||
const result = t.isBlockStatement(node.body)
|
||||
? node.body.body.length === 1 && t.isReturnStatement(node.body.body[0])
|
||||
? node.body.body[0].argument
|
||||
: undefined
|
||||
: node.body;
|
||||
return (
|
||||
t.isIdentifier(parameter) &&
|
||||
t.isIdentifier(result) &&
|
||||
resolveSemanticBindingState(state, parameter, parameter.name) !==
|
||||
undefined &&
|
||||
resolveSemanticBindingState(state, parameter, parameter.name) ===
|
||||
resolveSemanticBindingState(state, result, result.name)
|
||||
);
|
||||
};
|
||||
|
||||
const unprojectedInitializer = (
|
||||
binding: JavaScriptSemanticBindingState | undefined,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): t.Node | undefined => {
|
||||
const initializer = semanticStableInitializer(binding, state);
|
||||
return initializer?.projection.length === 0 ? initializer.node : undefined;
|
||||
};
|
||||
|
||||
/** Match operations and lexical roles, allowing single-statement control blocks. */
|
||||
const canonicalRoles = (
|
||||
actual: t.Node,
|
||||
pattern: t.Node,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): ReadonlyMap<string, JavaScriptSemanticBindingState> | undefined => {
|
||||
const roles = new Map<string, JavaScriptSemanticBindingState>();
|
||||
const used = new Map<string, string>();
|
||||
const pending: { actual: t.Node; pattern: t.Node; parent: t.Node | null }[] =
|
||||
[{ actual, pattern, parent: null }];
|
||||
while (pending.length !== 0) {
|
||||
const pair = pending.pop();
|
||||
if (pair === undefined) return undefined;
|
||||
const { parent } = pair;
|
||||
const controlBody =
|
||||
(t.isIfStatement(parent) &&
|
||||
(parent.consequent === pair.pattern ||
|
||||
parent.alternate === pair.pattern)) ||
|
||||
(t.isForStatement(parent) && parent.body === pair.pattern);
|
||||
const node = controlBody ? controlBodyOperation(pair.actual) : pair.actual;
|
||||
const expected = controlBody
|
||||
? controlBodyOperation(pair.pattern)
|
||||
: pair.pattern;
|
||||
if (node.type !== expected.type) return undefined;
|
||||
const literalKey =
|
||||
parent !== null &&
|
||||
((t.isMemberExpression(parent) &&
|
||||
!parent.computed &&
|
||||
parent.property === expected) ||
|
||||
(t.isObjectProperty(parent) &&
|
||||
!parent.computed &&
|
||||
parent.key === expected));
|
||||
if (t.isIdentifier(expected) && t.isIdentifier(node) && !literalKey) {
|
||||
const binding = resolveSemanticBindingState(state, node, node.name);
|
||||
if (
|
||||
binding === undefined ||
|
||||
(roles.has(expected.name) && roles.get(expected.name) !== binding) ||
|
||||
(used.has(binding.bindingId) &&
|
||||
used.get(binding.bindingId) !== expected.name)
|
||||
)
|
||||
return undefined;
|
||||
roles.set(expected.name, binding);
|
||||
used.set(binding.bindingId, expected.name);
|
||||
}
|
||||
const visitorKeys = javaScriptAstChildKeys(expected);
|
||||
for (const [key, field] of Object.entries(
|
||||
t.NODE_FIELDS[expected.type] ?? {},
|
||||
)) {
|
||||
if (
|
||||
visitorKeys.includes(key) ||
|
||||
(t.isIdentifier(expected) && key === "name" && !literalKey)
|
||||
)
|
||||
continue;
|
||||
const fallback: unknown = Reflect.get(field, "default");
|
||||
if (
|
||||
JSON.stringify(Reflect.get(node, key) ?? fallback) !==
|
||||
JSON.stringify(Reflect.get(expected, key) ?? fallback)
|
||||
)
|
||||
return undefined;
|
||||
}
|
||||
const children = childNodes(node),
|
||||
expectedChildren = childNodes(expected);
|
||||
if (children.length !== expectedChildren.length) return undefined;
|
||||
for (const [index, child] of children.entries()) {
|
||||
const expectedChild = expectedChildren[index];
|
||||
if (expectedChild !== undefined)
|
||||
pending.push({
|
||||
actual: child,
|
||||
pattern: expectedChild,
|
||||
parent: expected,
|
||||
});
|
||||
}
|
||||
}
|
||||
return roles;
|
||||
};
|
||||
|
||||
// Braces around one control-body statement do not add operations. Keep other
|
||||
// blocks, directives and extra statements intact; their semantics need proof.
|
||||
// Lexical declarations/references still pass through canonicalRoles' bijection.
|
||||
const controlBodyOperation = (node: t.Node): t.Node => {
|
||||
while (
|
||||
t.isBlockStatement(node) &&
|
||||
node.directives.length === 0 &&
|
||||
node.body.length === 1
|
||||
) {
|
||||
const statement = node.body[0];
|
||||
if (statement === undefined) break;
|
||||
node = statement;
|
||||
}
|
||||
return node;
|
||||
};
|
||||
@@ -0,0 +1,147 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
classifyPackageImportSpecifier,
|
||||
classifyPackageImportTargetString,
|
||||
lookupExactPackageImport,
|
||||
} from "./javascriptPackageImportAliases.js";
|
||||
|
||||
describe("package import specifier classification", () => {
|
||||
it("treats an exact hash alias as an exact key", () => {
|
||||
expect(classifyPackageImportSpecifier("#config")).toEqual({
|
||||
kind: "exact",
|
||||
key: "#config",
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["#internal/env", "#/hidden"])(
|
||||
"treats %j as an exact key",
|
||||
(specifier) => {
|
||||
expect(classifyPackageImportSpecifier(specifier)).toEqual({
|
||||
kind: "exact",
|
||||
key: specifier,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["#", "#/", "#utils/"])(
|
||||
"rejects reserved specifier %j",
|
||||
(specifier) => {
|
||||
expect(classifyPackageImportSpecifier(specifier)).toEqual({
|
||||
kind: "invalid",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["#internal/*", "#*"])(
|
||||
"leaves pattern specifier %j unresolved",
|
||||
(specifier) => {
|
||||
expect(classifyPackageImportSpecifier(specifier)).toEqual({
|
||||
kind: "pattern",
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("exact package import lookup", () => {
|
||||
it("returns the exact target without falling through to another key", () => {
|
||||
expect(
|
||||
lookupExactPackageImport(
|
||||
{ "#config": "./config.cjs", "#other": "./other.cjs" },
|
||||
"#config",
|
||||
),
|
||||
).toEqual({
|
||||
kind: "found",
|
||||
target: "./config.cjs",
|
||||
declared: ["#config", "#other"],
|
||||
});
|
||||
});
|
||||
|
||||
it("names declared exact keys when the requested alias is absent", () => {
|
||||
expect(
|
||||
lookupExactPackageImport({ "#config": "./config.cjs" }, "#missing"),
|
||||
).toEqual({
|
||||
kind: "missing-key",
|
||||
declared: ["#config"],
|
||||
});
|
||||
});
|
||||
|
||||
it("does not claim a miss when the map only has pattern keys", () => {
|
||||
expect(
|
||||
lookupExactPackageImport({ "#internal/*": "./src/*.js" }, "#internal/a"),
|
||||
).toEqual({
|
||||
kind: "pattern-unresolved",
|
||||
declared: ["#internal/*"],
|
||||
});
|
||||
});
|
||||
|
||||
it("still selects an exact key when the same map also has patterns", () => {
|
||||
expect(
|
||||
lookupExactPackageImport(
|
||||
{ "#config": "./config.cjs", "#internal/*": "./src/*.js" },
|
||||
"#config",
|
||||
),
|
||||
).toEqual({
|
||||
kind: "found",
|
||||
target: "./config.cjs",
|
||||
declared: ["#config", "#internal/*"],
|
||||
});
|
||||
});
|
||||
|
||||
it.each([undefined, null, "./config.cjs", ["#config"], 7] as const)(
|
||||
"treats non-object imports value %j as an undefined map",
|
||||
(imports) => {
|
||||
expect(lookupExactPackageImport(imports, "#config")).toEqual({
|
||||
kind: "undefined-map",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("does not treat a pattern key as an exact match for itself", () => {
|
||||
expect(
|
||||
lookupExactPackageImport({ "#internal/*": "./src/*.js" }, "#internal/*"),
|
||||
).toEqual({
|
||||
kind: "pattern-unresolved",
|
||||
declared: ["#internal/*"],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("package import target string classification", () => {
|
||||
it("keeps package-local relative targets", () => {
|
||||
expect(classifyPackageImportTargetString("./config.cjs")).toEqual({
|
||||
kind: "relative",
|
||||
target: "./config.cjs",
|
||||
});
|
||||
});
|
||||
|
||||
it("marks recursive hash aliases as recursive", () => {
|
||||
expect(classifyPackageImportTargetString("#other")).toEqual({
|
||||
kind: "recursive",
|
||||
target: "#other",
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["lodash", "pkg/subpath"])(
|
||||
"marks %j as an external-package target",
|
||||
(target) => {
|
||||
expect(classifyPackageImportTargetString(target)).toEqual({
|
||||
kind: "external-package",
|
||||
target,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
"../outside.js",
|
||||
"/outside.js",
|
||||
"https://example.invalid/mod.js",
|
||||
"file:///outside.js",
|
||||
"node:fs",
|
||||
])("marks %j as an invalid import target", (target) => {
|
||||
expect(classifyPackageImportTargetString(target)).toEqual({
|
||||
kind: "invalid",
|
||||
target,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* Exact package-private import-alias lookup. Node resolves `#` specifiers
|
||||
* against the importer's enclosing package `imports` map; this module owns the
|
||||
* specifier and exact-key rules. Condition, array, and null target selection
|
||||
* stay with the shared package-target machinery. Wildcard keys, recursive
|
||||
* `#` targets, and external-package targets remain explicit unknowns.
|
||||
*/
|
||||
|
||||
/** How one `#` specifier participates in exact import-alias lookup. */
|
||||
export type PackageImportSpecifierClassification =
|
||||
| { readonly kind: "invalid" }
|
||||
| { readonly kind: "pattern" }
|
||||
| { readonly kind: "exact"; readonly key: string };
|
||||
|
||||
/** Outcome of looking up one exact `#` key in a package `imports` object. */
|
||||
export type PackageImportExactLookup =
|
||||
| { readonly kind: "undefined-map" }
|
||||
| {
|
||||
readonly kind: "missing-key";
|
||||
readonly declared: readonly string[];
|
||||
}
|
||||
| {
|
||||
readonly kind: "pattern-unresolved";
|
||||
readonly declared: readonly string[];
|
||||
}
|
||||
| {
|
||||
readonly kind: "found";
|
||||
readonly target: unknown;
|
||||
readonly declared: readonly string[];
|
||||
};
|
||||
|
||||
/** How a selected string target is interpreted for package-private imports. */
|
||||
export type PackageImportTargetClassification =
|
||||
| { readonly kind: "relative"; readonly target: string }
|
||||
| { readonly kind: "invalid"; readonly target: string }
|
||||
| { readonly kind: "recursive"; readonly target: string }
|
||||
| { readonly kind: "external-package"; readonly target: string };
|
||||
|
||||
/**
|
||||
* Classify a `#` module specifier before any package-scope walk.
|
||||
* `#` and names ending in `/` are invalid. Other literal keys, including
|
||||
* `#/…`, participate in exact lookup; wildcard expansion remains unsupported.
|
||||
*/
|
||||
export const classifyPackageImportSpecifier = (
|
||||
specifier: string,
|
||||
): PackageImportSpecifierClassification => {
|
||||
if (specifier === "#" || specifier.endsWith("/")) return { kind: "invalid" };
|
||||
if (specifier.includes("*")) return { kind: "pattern" };
|
||||
return { kind: "exact", key: specifier };
|
||||
};
|
||||
|
||||
/** True when an `imports` key is a pattern rather than an exact alias. */
|
||||
export const isPackageImportPatternKey = (key: string): boolean =>
|
||||
key.includes("*") || key.endsWith("/");
|
||||
|
||||
/**
|
||||
* Look up one exact `#` key in a package `imports` value.
|
||||
* A missing exact key is reported as missing when every declared key is also
|
||||
* exact; if the map contains pattern keys, the miss stays pattern-unresolved
|
||||
* rather than claiming the specifier is undefined.
|
||||
*/
|
||||
export const lookupExactPackageImport = (
|
||||
imports: unknown,
|
||||
key: string,
|
||||
): PackageImportExactLookup => {
|
||||
if (typeof imports !== "object" || imports === null || Array.isArray(imports))
|
||||
return { kind: "undefined-map" };
|
||||
const declared = Object.keys(imports);
|
||||
if (Object.hasOwn(imports, key) && !isPackageImportPatternKey(key))
|
||||
return {
|
||||
kind: "found",
|
||||
target: Reflect.get(imports, key),
|
||||
declared,
|
||||
};
|
||||
return declared.some(isPackageImportPatternKey)
|
||||
? { kind: "pattern-unresolved", declared }
|
||||
: { kind: "missing-key", declared };
|
||||
};
|
||||
|
||||
/**
|
||||
* Classify a selected string import target. Only package-local `./` paths are
|
||||
* resolved as files; recursive `#` aliases and bare packages stay unknown.
|
||||
* Parent-relative, absolute, and URL targets are invalid, allowing array
|
||||
* selection to skip them before choosing a package-local fallback.
|
||||
*/
|
||||
export const classifyPackageImportTargetString = (
|
||||
target: string,
|
||||
): PackageImportTargetClassification => {
|
||||
if (target.startsWith("./")) return { kind: "relative", target };
|
||||
if (
|
||||
target.startsWith("../") ||
|
||||
target.startsWith("/") ||
|
||||
URL.canParse(target)
|
||||
)
|
||||
return { kind: "invalid", target };
|
||||
if (target.startsWith("#")) return { kind: "recursive", target };
|
||||
return { kind: "external-package", target };
|
||||
};
|
||||
@@ -195,6 +195,32 @@ describe("tRPC binding identity and bundled syntax", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("retains one client initializer across variable redeclarations", () => {
|
||||
expect(
|
||||
rpcEndpoints(`
|
||||
var c;
|
||||
var c = createTRPCClient({});
|
||||
var c;
|
||||
c.users.query();
|
||||
|
||||
var replaced;
|
||||
var replaced = createTRPCClient({});
|
||||
replaced = pool;
|
||||
replaced.posts.query();
|
||||
|
||||
var initializedTwice = createTRPCClient({});
|
||||
var initializedTwice = pool;
|
||||
initializedTwice.comments.query();
|
||||
|
||||
var conditional;
|
||||
if (flag) { var conditional = createTRPCClient({}); }
|
||||
conditional.groups.query();
|
||||
`),
|
||||
).toEqual([
|
||||
{ kind: "network", value: "users", mechanism: "trpc:procedure:query" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("recognizes surviving factory names inside bundled call wrappers", () => {
|
||||
expect(
|
||||
rpcEndpoints(`
|
||||
|
||||
@@ -179,6 +179,34 @@ describe("JavaScript semantic analysis: calls 2", () => {
|
||||
).not.toBe(left.functionFingerprints[0]?.components.literalSetSha256);
|
||||
});
|
||||
|
||||
it("keeps nested callable syntax out of its owner's fingerprint", () => {
|
||||
const analyze = (nested: number, owned: number) =>
|
||||
analyzeJavaScriptSemantics(`
|
||||
function outer() {
|
||||
function inner() { return ${nested}; }
|
||||
const object = { method() { return ${nested}; } };
|
||||
class Nested { method() { return ${nested}; } }
|
||||
return ${owned};
|
||||
}
|
||||
`);
|
||||
const first = analyze(1, 2);
|
||||
const changedNested = analyze(3, 2);
|
||||
const changedOwner = analyze(1, 4);
|
||||
const syntax = (ir: typeof first) =>
|
||||
ir.functionFingerprints.map(({ components }) => ({
|
||||
ast: components.normalizedAstSha256,
|
||||
control: components.controlFlowSha256,
|
||||
literals: components.literalSetSha256,
|
||||
}));
|
||||
const original = syntax(first);
|
||||
expect(original).toHaveLength(4);
|
||||
expect(syntax(changedNested)[0]).toEqual(original[0]);
|
||||
for (const index of [1, 2, 3])
|
||||
expect(syntax(changedNested)[index]).not.toEqual(original[index]);
|
||||
expect(syntax(changedOwner)[0]).not.toEqual(original[0]);
|
||||
expect(syntax(changedOwner).slice(1)).toEqual(original.slice(1));
|
||||
});
|
||||
|
||||
it("keeps fingerprint relations ordered and effects scoped to their owner", () => {
|
||||
const ordered = analyzeJavaScriptSemantics(`
|
||||
function first() {}
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
import {
|
||||
semanticObjectPatternKeys,
|
||||
semanticStaticPropertyKey,
|
||||
semanticWriteTargets,
|
||||
} from "./javascriptAstValues.js";
|
||||
import type {
|
||||
JavaScriptSemanticAnalysisState,
|
||||
@@ -31,16 +32,14 @@ import {
|
||||
resolveSemanticBindingFromScope,
|
||||
semanticBindingId,
|
||||
semanticScopeId,
|
||||
semanticStableInitializer,
|
||||
semanticVariableScope,
|
||||
} from "./javascriptSemanticState.js";
|
||||
import {
|
||||
completeSemanticSteps,
|
||||
traverseJavaScriptAstSteps,
|
||||
} from "./javascriptSemanticTraversal.js";
|
||||
import {
|
||||
semanticNamespaceInteropOperand,
|
||||
semanticRequireOrigin,
|
||||
} from "./javascriptSemanticRequireOrigin.js";
|
||||
import { semanticRequireOrigin } from "./javascriptSemanticRequireOrigin.js";
|
||||
import { collectSemanticMemberMutationsSteps } from "./javascriptSemanticMemberMutations.js";
|
||||
import {
|
||||
collectSemanticReturns,
|
||||
@@ -49,7 +48,7 @@ import {
|
||||
import { collectJavaScriptDerivedSemanticsSteps } from "./javascriptSemanticDerivedAnalysis.js";
|
||||
import { evaluateSemanticProvenance } from "./javascriptSemanticValues.js";
|
||||
import {
|
||||
collectElectronMemberWritesSteps,
|
||||
collectJavaScriptIdentityWritesSteps,
|
||||
electronExportPath,
|
||||
electronMemberPath,
|
||||
ELECTRON_MODULE,
|
||||
@@ -64,6 +63,8 @@ import {
|
||||
} from "./javascriptSourceParser.js";
|
||||
|
||||
import { isJavaScriptRpcClientFactory } from "./javascriptRpcEndpoints.js";
|
||||
import { createSemanticModuleInterop } from "./javascriptModuleInterop.js";
|
||||
import { SemanticPropertyPathCoverage } from "./javascriptSemanticPropertyPaths.js";
|
||||
|
||||
interface BindPatternInput {
|
||||
readonly pattern: t.Node;
|
||||
@@ -205,13 +206,10 @@ export function* classifyParsedJavaScriptRpcClientRootsSteps(
|
||||
if (binding === undefined) return;
|
||||
let client = clients.get(binding.bindingId);
|
||||
if (client === undefined) {
|
||||
const [initializer] = binding.initializers;
|
||||
const initializer = semanticStableInitializer(binding, state);
|
||||
client =
|
||||
initializer !== undefined &&
|
||||
initializer.projection.length === 0 &&
|
||||
binding.initializers.length === 1 &&
|
||||
!binding.definitions.some(({ kind }) => kind === "assignment") &&
|
||||
!state.conditionalInitializers.has(initializer.node) &&
|
||||
isJavaScriptRpcClientFactory(initializer.node);
|
||||
clients.set(binding.bindingId, client);
|
||||
}
|
||||
@@ -374,6 +372,9 @@ export function* classifyParsedJavaScriptElectronBindingsSteps(
|
||||
const facts = new Map<number, readonly string[]>();
|
||||
const state = createState(file.program);
|
||||
yield* collectDefinitionsSteps(file.program, state);
|
||||
const interop = createSemanticModuleInterop(state);
|
||||
const writes = new SemanticPropertyPathCoverage();
|
||||
let collectedWrites = false;
|
||||
const exportsByBinding = new Map<string, readonly string[] | null>();
|
||||
const rootExport = (root: t.Node): readonly string[] | undefined => {
|
||||
if (t.isIdentifier(root)) {
|
||||
@@ -382,23 +383,45 @@ export function* classifyParsedJavaScriptElectronBindingsSteps(
|
||||
if (binding === undefined) return undefined;
|
||||
let exported = exportsByBinding.get(binding.bindingId);
|
||||
if (exported === undefined) {
|
||||
exported = electronExport(binding, state);
|
||||
exported = electronExport(binding, state, interop);
|
||||
exportsByBinding.set(binding.bindingId, exported);
|
||||
}
|
||||
return exported ?? undefined;
|
||||
return collectedWrites && interop.invalidated(binding)
|
||||
? undefined
|
||||
: (exported ?? undefined);
|
||||
}
|
||||
const origin = semanticRequireOrigin(
|
||||
semanticNamespaceInteropOperand(root, state) ?? root,
|
||||
state,
|
||||
)?.origin;
|
||||
const wrapped = interop.callOrigin(root);
|
||||
const origin =
|
||||
wrapped === undefined
|
||||
? semanticRequireOrigin(root, state)?.origin
|
||||
: collectedWrites && interop.invalidatedCall(root)
|
||||
? undefined
|
||||
: wrapped.origin;
|
||||
return origin !== undefined && ELECTRON_MODULE.test(origin.specifier)
|
||||
? electronExportPath(origin.importedPath)
|
||||
: undefined;
|
||||
};
|
||||
const writes = yield* collectElectronMemberWritesSteps(
|
||||
yield* collectJavaScriptIdentityWritesSteps(
|
||||
file.program,
|
||||
rootExport,
|
||||
(root, kind) => {
|
||||
if (kind === "opaque-call") return interop.opaqueMutationPath(root);
|
||||
const exported = kind === "binding" ? undefined : rootExport(root);
|
||||
return exported === undefined
|
||||
? (interop.intrinsicPath(root) ??
|
||||
(kind === "member"
|
||||
? interop.boundIntrinsic(root)?.path
|
||||
: undefined))
|
||||
: ["electron", ...exported];
|
||||
},
|
||||
interop.intrinsicInvocation,
|
||||
interop.staticString,
|
||||
interop.isFreshObject,
|
||||
(node, path) => {
|
||||
if (path[0] === "electron") writes.retain(path);
|
||||
else interop.retainWrite(node, path);
|
||||
},
|
||||
);
|
||||
collectedWrites = true;
|
||||
yield* traverseJavaScriptAstSteps(file.program, {
|
||||
enter: (node) => {
|
||||
if (
|
||||
@@ -409,7 +432,10 @@ export function* classifyParsedJavaScriptElectronBindingsSteps(
|
||||
return;
|
||||
const { root, members } = electronMemberPath(node.callee);
|
||||
const exported = rootExport(root);
|
||||
if (exported !== undefined && !writes.covers([...exported, ...members]))
|
||||
if (
|
||||
exported !== undefined &&
|
||||
!writes.covers(["electron", ...exported, ...members])
|
||||
)
|
||||
facts.set(root.start ?? -1, exported);
|
||||
},
|
||||
});
|
||||
@@ -421,19 +447,16 @@ export function* classifyParsedJavaScriptElectronBindingsSteps(
|
||||
const electronExport = (
|
||||
binding: JavaScriptSemanticBindingState,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
interop: ReturnType<typeof createSemanticModuleInterop>,
|
||||
): readonly string[] | null => {
|
||||
const initializers = namespacePreservingInitializers(binding, state);
|
||||
if (initializers === undefined) return null;
|
||||
const directOrigin = bindingOrigin(binding, initializers, state);
|
||||
const [initializer] = initializers;
|
||||
if (
|
||||
directOrigin === undefined &&
|
||||
(initializer === undefined ||
|
||||
initializers.length !== 1 ||
|
||||
initializers.length !== binding.initializers.length ||
|
||||
state.conditionalInitializers.has(initializer.node))
|
||||
)
|
||||
return null;
|
||||
const reassigned = binding.definitions.some(
|
||||
({ kind }) => kind === "assignment",
|
||||
);
|
||||
const converted = interop.origin(binding);
|
||||
if (reassigned && converted === undefined) return null;
|
||||
const directOrigin = converted?.origin ?? bindingOrigin(binding, state);
|
||||
const initializer = semanticStableInitializer(binding, state);
|
||||
if (directOrigin === undefined && initializer === undefined) return null;
|
||||
const provenance =
|
||||
directOrigin === undefined
|
||||
? evaluateSemanticProvenance(binding, state)
|
||||
@@ -448,66 +471,17 @@ const electronExport = (
|
||||
: null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the initializers that can change which module a binding names.
|
||||
* Bundlers emit `name = __toESM(name)` after a CommonJS require; rewrapping
|
||||
* the binding's own value keeps every member, so it is not a reassignment.
|
||||
*/
|
||||
const namespacePreservingInitializers = (
|
||||
binding: JavaScriptSemanticBindingState,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): JavaScriptSemanticBindingState["initializers"] | undefined => {
|
||||
const initializers = binding.initializers.filter(
|
||||
({ node }) => !rewrapsOwnNamespace(binding, node, state),
|
||||
);
|
||||
const rewraps = binding.initializers.length - initializers.length;
|
||||
const assignments = binding.definitions.filter(
|
||||
({ kind }) => kind === "assignment",
|
||||
).length;
|
||||
return assignments === rewraps ? initializers : undefined;
|
||||
};
|
||||
|
||||
const rewrapsOwnNamespace = (
|
||||
binding: JavaScriptSemanticBindingState,
|
||||
node: t.Node,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): boolean => {
|
||||
const assignment = state.parentsByNode.get(node);
|
||||
const operand = semanticNamespaceInteropOperand(node, state);
|
||||
return (
|
||||
t.isAssignmentExpression(assignment) &&
|
||||
assignment.operator === "=" &&
|
||||
assignment.right === node &&
|
||||
t.isIdentifier(assignment.left, { name: binding.name }) &&
|
||||
t.isIdentifier(operand, { name: binding.name }) &&
|
||||
!semanticResolutionBlocked(state, operand, operand.name) &&
|
||||
resolveSemanticBindingState(state, operand, operand.name) === binding
|
||||
);
|
||||
};
|
||||
|
||||
const bindingOrigin = (
|
||||
binding: JavaScriptSemanticBindingState,
|
||||
initializers: JavaScriptSemanticBindingState["initializers"],
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): JavaScriptModuleOrigin | undefined => {
|
||||
if (binding.directOrigins.length > 0)
|
||||
return binding.directOrigins.length === 1
|
||||
? binding.directOrigins[0]
|
||||
: undefined;
|
||||
const [initializer] = initializers;
|
||||
// A var/let declaration permits writes without proving one occurred.
|
||||
// Require one unconditional initializer and no actual binding writes.
|
||||
if (
|
||||
initializer === undefined ||
|
||||
initializers.length !== 1 ||
|
||||
state.conditionalInitializers.has(initializer.node)
|
||||
)
|
||||
return undefined;
|
||||
const origin = semanticRequireOrigin(
|
||||
semanticNamespaceInteropOperand(initializer.node, state) ??
|
||||
initializer.node,
|
||||
state,
|
||||
)?.origin;
|
||||
const initializer = semanticStableInitializer(binding, state);
|
||||
if (initializer === undefined) return undefined;
|
||||
const origin = semanticRequireOrigin(initializer.node, state)?.origin;
|
||||
const projection = initializer.projection;
|
||||
return origin === undefined ||
|
||||
!projection.every((key): key is string => typeof key === "string")
|
||||
@@ -650,10 +624,11 @@ function* collectDefinitionsSteps(
|
||||
for (const [index, { body, scope, parameters }] of functionBodies.entries()) {
|
||||
if (index % 64 === 0) yield;
|
||||
for (const parameter of parameters)
|
||||
for (const identifier of assignedPatternIdentifiers(
|
||||
for (const identifier of semanticWriteTargets(
|
||||
t.isTSParameterProperty(parameter) ? parameter.parameter : parameter,
|
||||
))
|
||||
copyParameterToBody({ identifier, body, scope, state });
|
||||
if (t.isIdentifier(identifier))
|
||||
copyParameterToBody({ identifier, body, scope, state });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -801,16 +776,18 @@ const bindAssignment = (
|
||||
state,
|
||||
);
|
||||
else
|
||||
for (const identifier of assignedPatternIdentifiers(node.left))
|
||||
addAssignment(identifier, node, scope, state);
|
||||
for (const identifier of semanticWriteTargets(node.left))
|
||||
if (t.isIdentifier(identifier))
|
||||
addAssignment(identifier, node, scope, state);
|
||||
} else if (t.isUpdateExpression(node) && t.isIdentifier(node.argument))
|
||||
addAssignment(node.argument, node, scope, state);
|
||||
else if (t.isForOfStatement(node) || t.isForInStatement(node))
|
||||
for (const pattern of t.isVariableDeclaration(node.left)
|
||||
? node.left.declarations.map(({ id }) => id)
|
||||
: [node.left]) {
|
||||
for (const identifier of assignedPatternIdentifiers(pattern))
|
||||
addAssignment(identifier, node, scope, state);
|
||||
for (const identifier of semanticWriteTargets(pattern))
|
||||
if (t.isIdentifier(identifier))
|
||||
addAssignment(identifier, node, scope, state);
|
||||
if (t.isForOfStatement(node))
|
||||
// Keep the loop value unknown, but preserve references yielded into
|
||||
// each bound slot so writes/escapes can reach their iterable origins.
|
||||
@@ -825,30 +802,6 @@ const bindAssignment = (
|
||||
}
|
||||
};
|
||||
|
||||
const assignedPatternIdentifiers = (
|
||||
pattern: t.Node,
|
||||
): readonly t.Identifier[] => {
|
||||
const identifiers: t.Identifier[] = [];
|
||||
const pending = [pattern];
|
||||
while (pending.length > 0) {
|
||||
const node = pending.pop();
|
||||
if (node === undefined) continue;
|
||||
if (t.isIdentifier(node)) identifiers.push(node);
|
||||
else if (t.isRestElement(node)) pending.push(node.argument);
|
||||
else if (t.isAssignmentPattern(node)) pending.push(node.left);
|
||||
else if (t.isArrayPattern(node)) {
|
||||
for (const element of node.elements)
|
||||
if (element !== null) pending.push(element);
|
||||
} else if (t.isObjectPattern(node)) {
|
||||
for (const property of node.properties)
|
||||
pending.push(
|
||||
t.isRestElement(property) ? property.argument : property.value,
|
||||
);
|
||||
}
|
||||
}
|
||||
return identifiers;
|
||||
};
|
||||
|
||||
const nestedScope = (
|
||||
node: t.Node,
|
||||
parent: t.Node | null,
|
||||
|
||||
@@ -63,6 +63,35 @@ it("traverses a large tree in steps with the synchronous visit order (#1462)", (
|
||||
expect(stepped).toEqual(synchronous);
|
||||
});
|
||||
|
||||
it("skips child subtrees without changing sibling ancestry or exit callbacks", () => {
|
||||
const parsed = parseJavaScriptSource("[1, [2], 3]", "selection.js");
|
||||
if (parsed === null) throw new Error("Expected parsed source");
|
||||
const entered: number[] = [];
|
||||
const exited: number[] = [];
|
||||
const parents: string[][] = [];
|
||||
const steps = traverseJavaScriptAstSteps(parsed.program, {
|
||||
skip: (node) => node.type === "ArrayExpression" && node.start === 4,
|
||||
enter: (node, parent, readAncestors) => {
|
||||
if (node.type !== "NumericLiteral") return;
|
||||
entered.push(node.value);
|
||||
expect(readAncestors().at(-1)).toBe(parent);
|
||||
parents.push(readAncestors().map(({ type }) => type));
|
||||
},
|
||||
exit: (node) => {
|
||||
if (node.type === "NumericLiteral") exited.push(node.value);
|
||||
},
|
||||
});
|
||||
while (steps.next().done !== true) {
|
||||
// Complete the same cooperative traversal used by fingerprint collection.
|
||||
}
|
||||
expect(entered).toEqual([1, 3]);
|
||||
expect(exited).toEqual([1, 3]);
|
||||
expect(parents).toEqual([
|
||||
["Program", "ExpressionStatement", "ArrayExpression"],
|
||||
["Program", "ExpressionStatement", "ArrayExpression"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves receiver and Electron alias scope across traversal pauses (#1462)", () => {
|
||||
const padding = Array.from(
|
||||
{ length: 400 },
|
||||
|
||||
@@ -73,7 +73,7 @@ export function* collectJavaScriptSemanticFingerprintsSteps(
|
||||
const node = state.callableNodesById.get(callable.callableId);
|
||||
if (node === undefined) continue;
|
||||
yield;
|
||||
const syntax = yield* fingerprintSyntaxSteps(node, callable.callableId);
|
||||
const syntax = yield* fingerprintSyntaxSteps(node);
|
||||
const promiseEffects = promiseEffectsByOwner.get(callable.callableId) ?? [];
|
||||
const eventEffects = eventEffectsByOwner.get(callable.callableId) ?? [];
|
||||
const timerEffects = timerEffectsByOwner.get(callable.callableId) ?? [];
|
||||
@@ -164,28 +164,19 @@ interface FingerprintSyntax {
|
||||
|
||||
function* fingerprintSyntaxSteps(
|
||||
root: t.Node,
|
||||
targetCallableId: string,
|
||||
): Generator<void, FingerprintSyntax> {
|
||||
const normalizedTokens: string[] = [];
|
||||
const controlFlowTokens: string[] = [];
|
||||
const literals: string[] = [];
|
||||
const callableStack: string[] = [];
|
||||
yield* traverseJavaScriptAstSteps(root, {
|
||||
skip: (node) => semanticCallableIdForNode(node) !== null,
|
||||
enter: (node, parent) => {
|
||||
const callableId = semanticCallableIdForNode(node);
|
||||
if (callableId !== null) callableStack.push(callableId);
|
||||
if (callableStack.at(-1) !== targetCallableId) return;
|
||||
normalizedTokens.push(normalizedNodeToken(node, parent));
|
||||
const control = controlFlowToken(node);
|
||||
if (control !== null) controlFlowTokens.push(control);
|
||||
const literal = semanticLiteral(node);
|
||||
if (literal !== null) literals.push(literal);
|
||||
},
|
||||
exit: (node) => {
|
||||
const callableId = semanticCallableIdForNode(node);
|
||||
if (callableId !== null && callableStack.at(-1) === callableId)
|
||||
callableStack.pop();
|
||||
},
|
||||
});
|
||||
return { normalizedTokens, controlFlowTokens, literals };
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
|
||||
import { traverseJavaScriptAstSteps } from "./javascriptSemanticTraversal.js";
|
||||
import {
|
||||
semanticStaticPropertyKey,
|
||||
semanticMemberWriteTargets,
|
||||
semanticWriteTargets,
|
||||
unwrapJavaScriptExpression,
|
||||
} from "./javascriptAstValues.js";
|
||||
|
||||
@@ -401,14 +401,15 @@ export function* collectSemanticMemberMutationsSteps(
|
||||
markEscaped(expression.object, mutation);
|
||||
};
|
||||
const markTarget = (node: t.Node, mutation: t.Node): void => {
|
||||
for (const target of semanticMemberWriteTargets(node))
|
||||
markValue(
|
||||
target.object,
|
||||
[semanticStaticPropertyKey(target.property, target.computed)],
|
||||
new Set(),
|
||||
"write",
|
||||
mutation,
|
||||
);
|
||||
for (const target of semanticWriteTargets(node))
|
||||
if (!t.isIdentifier(target))
|
||||
markValue(
|
||||
target.object,
|
||||
[semanticStaticPropertyKey(target.property, target.computed)],
|
||||
new Set(),
|
||||
"write",
|
||||
mutation,
|
||||
);
|
||||
};
|
||||
yield* traverseJavaScriptAstSteps(program, {
|
||||
enter: (node, parent) => {
|
||||
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
resolveSemanticBindingState,
|
||||
semanticResolutionBlocked,
|
||||
type JavaScriptSemanticAnalysisState,
|
||||
type JavaScriptSemanticBindingState,
|
||||
} from "./javascriptSemanticState.js";
|
||||
import {
|
||||
semanticStaticPropertyKey,
|
||||
@@ -59,73 +58,3 @@ export const semanticRequireOrigin = (
|
||||
call: current,
|
||||
};
|
||||
};
|
||||
|
||||
// esbuild/Rolldown, TypeScript, and Babel emit these helpers for namespace
|
||||
// imports of CommonJS modules; each returns an object exposing every own
|
||||
// member of its operand, so member paths through the result are unchanged.
|
||||
// Helper bodies are not evaluated: recognition trusts a single program-scope
|
||||
// function definition under one of these emitted names.
|
||||
const NAMESPACE_INTEROP_HELPERS = new Set([
|
||||
"__importStar",
|
||||
"__toESM",
|
||||
"_interopRequireWildcard",
|
||||
]);
|
||||
|
||||
/** Return the module operand of a locally declared namespace interop helper. */
|
||||
export const semanticNamespaceInteropOperand = (
|
||||
node: t.Node,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): t.Expression | undefined => {
|
||||
const call = unwrapJavaScriptExpression(node).node;
|
||||
if (
|
||||
!t.isCallExpression(call) ||
|
||||
!t.isIdentifier(call.callee) ||
|
||||
!NAMESPACE_INTEROP_HELPERS.has(call.callee.name) ||
|
||||
semanticResolutionBlocked(state, call.callee, call.callee.name)
|
||||
)
|
||||
return undefined;
|
||||
const helper = resolveSemanticBindingState(
|
||||
state,
|
||||
call.callee,
|
||||
call.callee.name,
|
||||
);
|
||||
const [operand] = call.arguments;
|
||||
return helper !== undefined &&
|
||||
emittedInteropHelper(helper, state) &&
|
||||
t.isExpression(operand)
|
||||
? operand
|
||||
: undefined;
|
||||
};
|
||||
|
||||
// Emitters declare each helper once at program scope as a function, an
|
||||
// arrow/function expression, or `(this && this.name) || <function>`.
|
||||
const emittedInteropHelper = (
|
||||
helper: JavaScriptSemanticBindingState,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): boolean => {
|
||||
const [initializer] = helper.initializers;
|
||||
if (
|
||||
initializer === undefined ||
|
||||
helper.initializers.length !== 1 ||
|
||||
helper.definitions.length !== 1 ||
|
||||
(helper.kind !== "function" && helper.kind !== "variable") ||
|
||||
state.scopesById.get(helper.scopeId)?.kind !== "program"
|
||||
)
|
||||
return false;
|
||||
const value = unwrapJavaScriptExpression(initializer.node).node;
|
||||
const emitted =
|
||||
t.isLogicalExpression(value, { operator: "||" }) &&
|
||||
t.isLogicalExpression(unwrapJavaScriptExpression(value.left).node, {
|
||||
operator: "&&",
|
||||
})
|
||||
? unwrapJavaScriptExpression(value.right).node
|
||||
: value;
|
||||
return (
|
||||
t.isFunctionDeclaration(emitted) ||
|
||||
t.isFunctionExpression(emitted) ||
|
||||
t.isArrowFunctionExpression(emitted) ||
|
||||
(t.isCallExpression(emitted) &&
|
||||
(t.isFunctionExpression(emitted.callee) ||
|
||||
t.isArrowFunctionExpression(emitted.callee)))
|
||||
);
|
||||
};
|
||||
|
||||
@@ -75,6 +75,30 @@ export interface JavaScriptSemanticAnalysisState {
|
||||
readonly conditionalInitializers: WeakSet<t.Node>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return one unconditional source initializer for a declared lexical binding.
|
||||
* Repeated variable declarations without another initializer do not write it.
|
||||
* This establishes a stable source fact only; it does not prove immutability or
|
||||
* that the declaration has executed at a particular program point.
|
||||
*/
|
||||
export const semanticStableInitializer = (
|
||||
binding: JavaScriptSemanticBindingState | undefined,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): JavaScriptSemanticBindingState["initializers"][number] | undefined => {
|
||||
const [initializer] = binding?.initializers ?? [];
|
||||
const [definition] = binding?.definitions ?? [];
|
||||
return binding !== undefined &&
|
||||
((definition?.kind === "variable" &&
|
||||
binding.definitions.every(({ kind }) => kind === "variable")) ||
|
||||
(binding.definitions.length === 1 &&
|
||||
(definition?.kind === "function" || definition?.kind === "class"))) &&
|
||||
binding.initializers.length === 1 &&
|
||||
initializer !== undefined &&
|
||||
!state.conditionalInitializers.has(initializer.node)
|
||||
? initializer
|
||||
: undefined;
|
||||
};
|
||||
|
||||
/** Return the active scope from a non-empty construction stack. */
|
||||
export const currentSemanticScope = (
|
||||
stack: readonly JavaScriptSemanticScopeState[],
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as t from "@babel/types";
|
||||
|
||||
/**
|
||||
* Visit every Babel AST node in deterministic source-tree order.
|
||||
* Visit Babel AST nodes in deterministic source-tree order, excluding skipped subtrees.
|
||||
*
|
||||
* `readAncestors` returns a snapshot during `enter`, outermost-first and
|
||||
* ending with the direct parent. Callers
|
||||
@@ -17,6 +17,8 @@ export const traverseJavaScriptAst = (
|
||||
|
||||
/** Callbacks for one deterministic AST traversal. */
|
||||
export interface JavaScriptAstVisitor {
|
||||
/** Omit a child and its subtree without entering or exiting it. */
|
||||
readonly skip?: (node: t.Node) => boolean;
|
||||
readonly enter: (
|
||||
node: t.Node,
|
||||
parent: t.Node | null,
|
||||
@@ -50,6 +52,7 @@ export function* traverseJavaScriptAstSteps(
|
||||
current.nextIndex += 1;
|
||||
if (visited % 1024 === 0) yield;
|
||||
visited += 1;
|
||||
if (visitor.skip?.(child) === true) continue;
|
||||
pending.push(enter(child, current.node));
|
||||
} else {
|
||||
visitor.exit?.(current.node, current.parent);
|
||||
@@ -82,8 +85,7 @@ interface TraversalFrame {
|
||||
* not be reintroduced (they diverge on loc/comment fields and ordering).
|
||||
*/
|
||||
export const childNodes = (node: t.Node): t.Node[] => {
|
||||
const keys = t.VISITOR_KEYS[node.type];
|
||||
if (keys === undefined) return [];
|
||||
const keys = javaScriptAstChildKeys(node);
|
||||
const children: t.Node[] = [];
|
||||
for (const key of keys) {
|
||||
const value: unknown = Reflect.get(node, key);
|
||||
@@ -98,3 +100,7 @@ export const childNodes = (node: t.Node): t.Node[] => {
|
||||
}
|
||||
return children;
|
||||
};
|
||||
|
||||
/** Child-bearing fields; shared by traversal and structural AST comparison. */
|
||||
export const javaScriptAstChildKeys = (node: t.Node): readonly string[] =>
|
||||
t.VISITOR_KEYS[node.type] ?? [];
|
||||
|
||||
@@ -2,7 +2,9 @@ import { isAbsolute, relative, sep } from "node:path";
|
||||
import { z } from "zod";
|
||||
|
||||
/**
|
||||
* Preserve selected filesystem names while rejecting OS-invalid NUL bytes.
|
||||
* Reject OS-invalid NUL bytes in a local filesystem name. This is not a path
|
||||
* shape check: an empty or relative value is admitted here and narrowed by the
|
||||
* callers that need a nonempty or absolute path.
|
||||
*
|
||||
* The pattern spells NUL as `\x00` rather than `\u0000`. Both accept exactly the
|
||||
* same strings. The hex form also avoids the short `\0` spelling rejected by
|
||||
@@ -10,11 +12,13 @@ import { z } from "zod";
|
||||
* one advertised pattern cannot compile. See `offsetDateTimeSchema` for the
|
||||
* same hex-escape convention.
|
||||
*/
|
||||
export const localPathStringSchema = z
|
||||
export const nulFreeStringSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.regex(/^[^\x00]*$/u, "Local filesystem paths cannot contain NUL");
|
||||
|
||||
/** A selected local filesystem path: nonempty and free of NUL bytes. */
|
||||
export const localPathStringSchema = nulFreeStringSchema.min(1);
|
||||
|
||||
/** Test lexical containment on the host platform; callers must resolve symlinks first. */
|
||||
export const isPathWithinRoot = (root: string, path: string): boolean => {
|
||||
const value = relative(root, path);
|
||||
|
||||
@@ -84,7 +84,7 @@ export const nativeLoadImageCheckSchema = z.strictObject({
|
||||
});
|
||||
|
||||
/** Read-only native image verification; verified applies only to declared coverage. */
|
||||
export const nativeLoadImageSchema = z.discriminatedUnion("status", [
|
||||
export const nativeLoadImageSchema = z.union([
|
||||
z.strictObject({
|
||||
status: z.literal("unsupported"),
|
||||
reason: z.string().min(1),
|
||||
@@ -108,6 +108,23 @@ export const nativeLoadImageSchema = z.discriminatedUnion("status", [
|
||||
checks: z.array(nativeLoadImageCheckSchema),
|
||||
limitations: z.array(z.string().min(1)),
|
||||
}),
|
||||
z.strictObject({
|
||||
status: z.enum(["verified", "mismatch"]),
|
||||
format: z.literal("raw-binary"),
|
||||
target_sha256: digest,
|
||||
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]),
|
||||
language_id: z.string().min(1),
|
||||
compiler_spec_id: z.string().min(1),
|
||||
base_address: address,
|
||||
file_bytes: integer.min(1),
|
||||
entry: z.strictObject({
|
||||
address: address,
|
||||
file_offset: z.literal(0),
|
||||
}),
|
||||
observations: nativeLoadImageObservationSchema,
|
||||
checks: z.array(nativeLoadImageCheckSchema),
|
||||
limitations: z.array(z.string().min(1)),
|
||||
}),
|
||||
]);
|
||||
|
||||
/** Provider-neutral native load-image result. */
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { executableFormatHintSchema } from "./dosCom.js";
|
||||
import {
|
||||
admitRawBinary,
|
||||
parseRawBinaryEntryPoint,
|
||||
rawBinarySelectionError,
|
||||
validateRawBinaryLength,
|
||||
} from "./rawBinary.js";
|
||||
|
||||
describe("headerless format hints", () => {
|
||||
it("admits dos-com and raw-binary names only", () => {
|
||||
expect(executableFormatHintSchema.safeParse("dos-com").success).toBe(true);
|
||||
expect(executableFormatHintSchema.safeParse("raw-binary").success).toBe(
|
||||
true,
|
||||
);
|
||||
expect(executableFormatHintSchema.safeParse("raw").success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("raw-binary entry addresses", () => {
|
||||
it("canonicalizes equivalent hex spellings without dropping the source", () => {
|
||||
const parsed = parseRawBinaryEntryPoint("0x08000000");
|
||||
expect(parsed).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
source: "0x08000000",
|
||||
canonical: "0x8000000",
|
||||
value: 0x8000000n,
|
||||
},
|
||||
});
|
||||
});
|
||||
it.each(["8000000", "0x", "0xgg", "0X8000000", ""])(
|
||||
"rejects malformed entry %s",
|
||||
(value) => {
|
||||
expect(parseRawBinaryEntryPoint(value).ok).toBe(false);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("raw-binary admission", () => {
|
||||
it("admits a little-endian ARM image mapped at the caller entry", () => {
|
||||
expect(
|
||||
admitRawBinary({
|
||||
architecture: "arm",
|
||||
entryPoint: "0x8000000",
|
||||
fileBytes: 4,
|
||||
}),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
architecture: "arm",
|
||||
entryPoint: "0x8000000",
|
||||
entryPointSource: "0x8000000",
|
||||
},
|
||||
});
|
||||
});
|
||||
it("rejects an empty file", () => {
|
||||
expect(validateRawBinaryLength(0).ok).toBe(false);
|
||||
expect(
|
||||
admitRawBinary({
|
||||
architecture: "x86",
|
||||
entryPoint: "0x1000",
|
||||
fileBytes: 0,
|
||||
}).ok,
|
||||
).toBe(false);
|
||||
});
|
||||
it("rejects a 32-bit mapping that exceeds the architecture width", () => {
|
||||
const result = admitRawBinary({
|
||||
architecture: "arm",
|
||||
entryPoint: "0xfffffffc",
|
||||
fileBytes: 8,
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("expected overflow rejection");
|
||||
expect(result.error).toContain("arm address width");
|
||||
});
|
||||
it("allows a 64-bit mapping that would overflow 32-bit ARM", () => {
|
||||
expect(
|
||||
admitRawBinary({
|
||||
architecture: "arm64",
|
||||
entryPoint: "0xfffffffc",
|
||||
fileBytes: 8,
|
||||
}).ok,
|
||||
).toBe(true);
|
||||
});
|
||||
it.each(["arm", "arm64"])(
|
||||
"rejects unaligned %s entries before provider selection",
|
||||
(architecture) => {
|
||||
for (const entryPoint of ["0x8000001", "0x8000002", "0x8000003"]) {
|
||||
expect(
|
||||
admitRawBinary({ architecture, entryPoint, fileBytes: 4 }),
|
||||
).toEqual({
|
||||
ok: false,
|
||||
error: `raw-binary ${architecture} entry_point ${entryPoint} must be 4-byte aligned`,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
it.each(["x86", "x86_64"])(
|
||||
"admits byte-aligned %s entries",
|
||||
(architecture) => {
|
||||
const admitted = admitRawBinary({
|
||||
architecture,
|
||||
entryPoint: "0x1001",
|
||||
fileBytes: 1,
|
||||
});
|
||||
if (!admitted.ok) throw new Error(admitted.error);
|
||||
expect(admitted.value.entryPoint).toBe("0x1001");
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("raw-binary selection pairing", () => {
|
||||
it("requires architecture and entry with format=raw-binary", () => {
|
||||
expect(rawBinarySelectionError({ format: "raw-binary" })).toBe(
|
||||
"format=raw-binary requires architecture and entry_point",
|
||||
);
|
||||
expect(
|
||||
rawBinarySelectionError({
|
||||
format: "raw-binary",
|
||||
architecture: "arm",
|
||||
entryPoint: "0x8000000",
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
it("rejects architecture or entry without format=raw-binary", () => {
|
||||
expect(
|
||||
rawBinarySelectionError({ architecture: "arm", entryPoint: "0x1" }),
|
||||
).toBe("architecture and entry_point apply only with format=raw-binary");
|
||||
expect(
|
||||
rawBinarySelectionError({ format: "dos-com", architecture: "x86" }),
|
||||
).toBe("architecture and entry_point apply only with format=raw-binary");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { BinaryArchitecture } from "./binaryTargetTypes.js";
|
||||
import type { ExecutableFormatHint } from "./dosCom.js";
|
||||
import { err, ok, type Result } from "./result.js";
|
||||
|
||||
/** Caller-visible CPU families admitted for headerless raw binaries. */
|
||||
export const BINARY_ARCHITECTURES = [
|
||||
"x86",
|
||||
"x86_64",
|
||||
"arm",
|
||||
"arm64",
|
||||
] as const satisfies readonly BinaryArchitecture[];
|
||||
|
||||
/** Provider-neutral CPU family for a caller-supplied raw-binary load. */
|
||||
export const binaryArchitectureSchema = z.enum(BINARY_ARCHITECTURES);
|
||||
|
||||
const RAW_BINARY_ENTRY_POINT = /^0x[0-9A-Fa-f]{1,16}$/u;
|
||||
|
||||
/** Hexadecimal load and entry address; file offset 0 is mapped here. */
|
||||
export const rawBinaryEntryPointSchema = z
|
||||
.string()
|
||||
.regex(RAW_BINARY_ENTRY_POINT, {
|
||||
message: "entry_point must be a hexadecimal address of the form 0x…",
|
||||
});
|
||||
|
||||
/** Canonicalized caller-supplied raw-binary entry with the original spelling. */
|
||||
export interface CanonicalRawBinaryEntry {
|
||||
readonly source: string;
|
||||
readonly canonical: string;
|
||||
readonly value: bigint;
|
||||
}
|
||||
|
||||
/** Parse a caller-supplied hex entry while preserving the source spelling. */
|
||||
export const parseRawBinaryEntryPoint = (
|
||||
value: string,
|
||||
): Result<CanonicalRawBinaryEntry, string> => {
|
||||
if (!RAW_BINARY_ENTRY_POINT.test(value))
|
||||
return err("entry_point must be a hexadecimal address of the form 0x…");
|
||||
const parsed = BigInt(value);
|
||||
return ok({
|
||||
source: value,
|
||||
canonical: `0x${parsed.toString(16)}`,
|
||||
value: parsed,
|
||||
});
|
||||
};
|
||||
|
||||
/** Reject empty or non-integral file extents for a headerless image. */
|
||||
export const validateRawBinaryLength = (
|
||||
length: number,
|
||||
): Result<null, string> =>
|
||||
Number.isSafeInteger(length) && length >= 1
|
||||
? ok(null)
|
||||
: err("raw-binary requires at least one file byte");
|
||||
|
||||
/** Admitted headerless load identity used by target resolution and profiles. */
|
||||
export interface RawBinaryAdmission {
|
||||
readonly architecture: Exclude<BinaryArchitecture, "mips">;
|
||||
readonly entryPoint: string;
|
||||
readonly entryPointSource: string;
|
||||
}
|
||||
|
||||
const addressWidth = (architecture: BinaryArchitecture): bigint =>
|
||||
architecture === "x86" || architecture === "arm"
|
||||
? 0xffffffffn
|
||||
: 0xffffffffffffffffn;
|
||||
|
||||
/** Validate architecture, entry, and that the mapped image fits the CPU width. */
|
||||
export const admitRawBinary = (input: {
|
||||
readonly architecture: unknown;
|
||||
readonly entryPoint: unknown;
|
||||
readonly fileBytes: number;
|
||||
}): Result<RawBinaryAdmission, string> => {
|
||||
const architecture = binaryArchitectureSchema.safeParse(input.architecture);
|
||||
if (!architecture.success)
|
||||
return err(
|
||||
"raw-binary format requires architecture (x86, x86_64, arm, or arm64)",
|
||||
);
|
||||
if (typeof input.entryPoint !== "string")
|
||||
return err(
|
||||
"raw-binary format requires entry_point as a hexadecimal address of the form 0x…",
|
||||
);
|
||||
const entry = parseRawBinaryEntryPoint(input.entryPoint);
|
||||
if (!entry.ok) return entry;
|
||||
if (
|
||||
(architecture.data === "arm" || architecture.data === "arm64") &&
|
||||
entry.value.value % 4n !== 0n
|
||||
)
|
||||
return err(
|
||||
`raw-binary ${architecture.data} entry_point ${entry.value.canonical} must be 4-byte aligned`,
|
||||
);
|
||||
const length = validateRawBinaryLength(input.fileBytes);
|
||||
if (!length.ok) return length;
|
||||
const last = entry.value.value + BigInt(input.fileBytes) - 1n;
|
||||
const max = addressWidth(architecture.data);
|
||||
if (entry.value.value > max || last > max)
|
||||
return err(
|
||||
`raw-binary mapping from ${entry.value.canonical} must fit in the ${architecture.data} address width`,
|
||||
);
|
||||
return ok({
|
||||
architecture: architecture.data,
|
||||
entryPoint: entry.value.canonical,
|
||||
entryPointSource: entry.value.source,
|
||||
});
|
||||
};
|
||||
|
||||
/** Describe the format/architecture/entry pairing without performing I/O. */
|
||||
export const rawBinarySelectionError = (input: {
|
||||
readonly format?: ExecutableFormatHint;
|
||||
readonly architecture?: unknown;
|
||||
readonly entryPoint?: unknown;
|
||||
}): string | undefined => {
|
||||
const hasArchitecture = input.architecture !== undefined;
|
||||
const hasEntry = input.entryPoint !== undefined;
|
||||
if (input.format === "raw-binary") {
|
||||
if (!hasArchitecture || !hasEntry)
|
||||
return "format=raw-binary requires architecture and entry_point";
|
||||
return undefined;
|
||||
}
|
||||
if (hasArchitecture || hasEntry)
|
||||
return "architecture and entry_point apply only with format=raw-binary";
|
||||
return undefined;
|
||||
};
|
||||
@@ -38,6 +38,18 @@ describe("managed projection admission", () => {
|
||||
});
|
||||
|
||||
describe("managed decoding bounds", () => {
|
||||
it("bounds new row identities without charging lookup replay or merging tables", () => {
|
||||
const budget = new ManagedDecodeBudget();
|
||||
budget.reserve(64 * 1024 * 1024 - 512, null);
|
||||
budget.reserveRow(2, 1, 100);
|
||||
budget.reserveRow(12, 1, 200);
|
||||
|
||||
expect(() => budget.reserveRow(2, 1, 100)).not.toThrow();
|
||||
expect(() => budget.reserveRow(2, 2, 300)).toThrow(ManagedReaderFailure);
|
||||
// A rejected row has no retained reservation; replay cannot bypass capacity.
|
||||
expect(() => budget.reserveRow(2, 2, 300)).toThrow(ManagedReaderFailure);
|
||||
});
|
||||
|
||||
it("keeps concurrent decoding bounds within one budget until released", () => {
|
||||
const budget = new ManagedDecodeBudget();
|
||||
const bound = 40 * 1024 * 1024;
|
||||
|
||||
@@ -15,6 +15,7 @@ interface CachedString {
|
||||
export class ManagedDecodeBudget {
|
||||
#remaining = MAX_METADATA_REPRESENTATION_BYTES;
|
||||
#transient = 0;
|
||||
readonly #rows = new Map<number, Set<number>>();
|
||||
readonly #strings = new Map<number, CachedString>();
|
||||
readonly #digests = new WeakMap<ArrayBufferLike, Map<string, string>>();
|
||||
|
||||
@@ -23,6 +24,18 @@ export class ManagedDecodeBudget {
|
||||
this.#remaining -= bytes;
|
||||
}
|
||||
|
||||
/** Retain one bookkeeping reservation per physical row, independently of lookup replay. */
|
||||
reserveRow(table: number, row: number, offset: number): void {
|
||||
let rows = this.#rows.get(table);
|
||||
if (rows?.has(row) === true) return;
|
||||
this.reserve(256, offset);
|
||||
if (rows === undefined) {
|
||||
rows = new Set<number>();
|
||||
this.#rows.set(table, rows);
|
||||
}
|
||||
rows.add(row);
|
||||
}
|
||||
|
||||
/** Bound a decoding allocation that stays live until `releaseTransient`; only retained output is reserved. */
|
||||
admitTransient(bytes: number, offset: number | null): void {
|
||||
this.#admit(bytes, offset);
|
||||
|
||||
@@ -245,8 +245,9 @@ export const metadataRowCursor = (
|
||||
"Metadata table is absent",
|
||||
start,
|
||||
);
|
||||
// Reserve per-row object/index bookkeeping before readers retain decoded facts.
|
||||
managedDecodeBudget(layout).reserve(256, start);
|
||||
// Temporary cursors may revisit a row while resolving owners or references.
|
||||
// Bind fixed retained bookkeeping to that row's identity, not each lookup.
|
||||
managedDecodeBudget(layout).reserveRow(table, row, start);
|
||||
return new MetadataRowCursor(
|
||||
bytes,
|
||||
start,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user