Compare commits

..
Author SHA1 Message Date
N0zoM1z0 c7fdd7e153 test(artifacts): share ASAR member fixture setup 2026-10-11 03:54:57 +08:00
N0zoM1z0 3c794a5cc0 Merge commit '5100a1a1a56b810c8246b8c7ed19ff42c4d9dbe1' into fix/ci-duplicate-boundaries-1603 2026-10-11 03:50:21 +08:00
N0zoM1z0 16caa5ca9b chore(ci): refresh maintenance checks against current main 2026-10-11 03:44:06 +08:00
N0zoM1z0 2a6bef5589 chore(ci): include current snapshot and runtime repairs 2026-10-11 01:50:32 +08:00
N0zoM1z0 cace19caad fix(ci): reconcile lifecycle checks with current main
Preserve failed event finalization across retries and current capture ownership checks. Retain Git unreadable-ref and bounded-heap Evidence coverage, pinned maintenance destinations, and explicit native binding facts.
2026-10-11 01:08:09 +08:00
N0zoM1z0 87b7bf8db1 fix(reference-source): distinguish Git API probes from failed reads 2026-10-10 16:59:30 +00:00
N0zoM1z0 3b66532e26 Merge commit '603d04ee3ac6ed496f84478164f832a9b5ce3b91' into fix/main-maintenance-ci-20261010
# Conflicts:
#	tests/process-global/updateMaintenance.test.ts
2026-10-10 16:36:42 +00:00
N0zoM1z0 3ad063b454 Merge remote-tracking branch 'origin/main' into fix/main-maintenance-ci-20261010 2026-10-10 16:34:18 +00:00
N0zoM1z0 69485e27f7 fix(ci): restore capture and maintenance regression checks 2026-10-10 16:34:17 +00:00
272 changed files with 2781 additions and 15266 deletions
@@ -9,22 +9,6 @@ that static analysis. Read findings, coverage, limitations and unknowns, then
follow a specific unanswered question. Older servers without `detail` return
the complete application Evidence inline when it fits.
When the connected schema advertises `max_heap_mb` and `analysis_timeout_ms`,
these select the isolated source analyzer's old-space heap and per-source
deadline. Defaults are 1024 MiB and 300000 ms. They do not change the MCP
process heap. Resource-limited analyses preserve completed static facts and
report partial semantic coverage with specific unknown scopes; this does not
mean the source is malformed. Inspect those limits before retrying a source.
When expanded relationships exceed the parent's available memory, inspect the
file's modules item view for retained `static_analysis` and
`semantic_module_analysis`. Their facts remain available even when graph links
are unknown. Cumulative result exhaustion can stop analysis before every file
is examined; the inventory and remaining unknown scopes distinguish that case.
Timeout or cancellation after source analysis begins retains partial Evidence
in the same session. A returned `error.details.partial_observation` reference
can be supplied directly to `inspect_analysis_view`. If the SDK cancels locally, retrieve its recorded ID from
the Evidence bundle before inspecting the partial analysis.
## Read a module without repeating analysis
Use the actual returned parent ID, on the same connection, as `source.evidence_id`.
@@ -152,7 +152,7 @@ context. PSP/stack/device state remains unmodeled. See [DOS guide](https://githu
### 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.
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.
## Offline PE resource inventory
+2 -2
View File
@@ -1,6 +1,6 @@
{
"_comment": "Test files are intentionally NOT excluded: the gate used to report zero clones because it skipped **/*.test.ts, hiding all test-tree duplication. Current actual is ~2.47% lines across src+ and tests/, down from 3.4% when tests were included. The 2.6% limit leaves modest headroom for ordinary changes; lower it as duplication is removed.",
"threshold": 2.6,
"_comment": "Test files are intentionally NOT excluded: the gate used to report zero clones because it skipped **/*.test.ts, hiding all test-tree duplication. Current actual is ~2.4% lines across src+ and tests/, down from 3.4% when tests were included. Lower this as duplication is removed.",
"threshold": 2.5,
"reporters": ["consoleFull"],
"ignore": [
"node_modules/**",
+10 -81
View File
@@ -120,8 +120,6 @@ public final class ReaGhidraBridge extends HeadlessScript {
);
private static final String[] CAPABILITIES = {
"annotate_native_function",
"set_address_name",
"set_addresses_names",
"inspect_native_load_image",
"read_bytes",
"address_to_file_offset",
@@ -376,12 +374,6 @@ public final class ReaGhidraBridge extends HeadlessScript {
case "resolve_native_call_targets" -> resolveNativeCallTargets(request.params);
case "xrefs" -> xrefs(request.params);
case "analyze_function" -> analyzeFunction(request.params);
case "set_address_name", "set_addresses_names" -> {
if (!descriptor.transport.equals("unix-socket"))
throw new RequestFailure("method_unavailable", "Windows P0 does not admit database mutation");
yield request.method.equals("set_address_name")
? setAddressName(request.params) : setAddressesNames(request.params);
}
case "annotate_native_function" -> {
if (!descriptor.transport.equals("unix-socket"))
throw new RequestFailure("method_unavailable", "Windows P0 does not admit database mutation");
@@ -425,8 +417,7 @@ public final class ReaGhidraBridge extends HeadlessScript {
result.addProperty("analysis_timed_out", timedOut);
result.add("capabilities", GSON.toJsonTree(
java.util.Arrays.stream(CAPABILITIES)
.filter(value -> !readOnly || !(value.equals("annotate_native_function")
|| value.equals("set_address_name") || value.equals("set_addresses_names")))
.filter(value -> !readOnly || !value.equals("annotate_native_function"))
.toArray(String[]::new)
));
result.add("target", target);
@@ -1036,11 +1027,11 @@ public final class ReaGhidraBridge extends HeadlessScript {
for (String field : List.of("name", "comment", "inline_comment")) {
if (params.has(field)) validateAnnotationText(requireText(params, field), field);
}
String leafName = params.has("name")
? annotationLeafName(function, requireString(params, "name")) : null;
int transaction = currentProgram.startTransaction("REA function annotations");
boolean commit = false;
try {
String leafName = params.has("name")
? symbolLeafName(function.getSymbol(), requireString(params, "name")) : null;
// Validate edits through Ghidra's own setters, including name rules.
// A later invalid name must roll back earlier comment writes.
for (String field : List.of("comment", "inline_comment")) {
@@ -1089,18 +1080,18 @@ public final class ReaGhidraBridge extends HeadlessScript {
}
}
private String symbolLeafName(Symbol symbol, String requested) throws ghidra.util.exception.InvalidInputException {
private String annotationLeafName(Function function, String requested) {
// Fully qualified readback must be usable as an idempotent rename input.
if (requested.equals(symbol.getName(true))) return symbol.getName();
String namespace = symbol.getParentNamespace().isGlobal()
? "" : symbol.getParentNamespace().getName(true);
if (requested.equals(procedureName(function))) return function.getName();
String namespace = function.getParentNamespace().isGlobal()
? "" : function.getParentNamespace().getName(true);
String prefix = namespace + "::";
if (!namespace.isEmpty() && requested.startsWith(prefix)) {
String leaf = requested.substring(prefix.length());
if (!leaf.isEmpty()) return leaf;
throw new ghidra.util.exception.InvalidInputException(
"Symbol name has an empty leaf within namespace " + namespace + " at " +
canonicalAddress(symbol.getAddress()) + ": " + requested);
throw new RequestFailure("invalid_function_name",
"Function name has an empty leaf within namespace " + namespace + " at " +
canonicalAddress(function.getEntryPoint()) + ": " + requested);
}
return requested;
}
@@ -1425,68 +1416,6 @@ public final class ReaGhidraBridge extends HeadlessScript {
return symbol == null ? JsonNull.INSTANCE : GSON.toJsonTree(symbol.getName(true));
}
// Analyst naming: a function entry renames the function, other addresses get a primary label.
private boolean applyAddressName(Address address, String name) throws Exception {
if (!currentProgram.getMemory().contains(address))
throw new RequestFailure("invalid_request", "Address is not mapped: " + canonicalAddress(address));
validateAnnotationText(name, "name");
int transaction = currentProgram.startTransaction("REA address name");
boolean commit = false;
try {
Function function = currentProgram.getFunctionManager().getFunctionAt(address);
String expected = name;
if (function != null) {
expected = symbolLeafName(function.getSymbol(), name);
function.setName(expected, SourceType.USER_DEFINED);
} else {
var table = currentProgram.getSymbolTable();
Symbol primary = table.getPrimarySymbol(address);
if (primary != null && !primary.isDynamic()) {
expected = symbolLeafName(primary, name);
primary.setName(expected, SourceType.USER_DEFINED);
} else {
Symbol created = table.createLabel(address, name, SourceType.USER_DEFINED);
created.setPrimary();
}
}
invalidateAnalysisCaches();
Symbol readback = currentProgram.getSymbolTable().getPrimarySymbol(address);
commit = readback != null && expected.equals(readback.getName());
return commit;
}
catch (ghidra.util.exception.InvalidInputException | ghidra.util.exception.DuplicateNameException exception) {
return false;
}
finally {
currentProgram.endTransaction(transaction, commit);
}
}
private JsonElement setAddressName(JsonObject params) throws Exception {
requireKeys(params, Set.of("document", "address", "name"));
requireDocument(params);
return GSON.toJsonTree(applyAddressName(requireAddress(params, "address"), requireString(params, "name")));
}
private JsonElement setAddressesNames(JsonObject params) throws Exception {
requireKeys(params, Set.of("document", "names"));
requireDocument(params);
if (!params.has("names") || !params.get("names").isJsonObject())
throw new RequestFailure("invalid_request", "names must be an object of address -> name");
JsonObject result = new JsonObject();
for (Map.Entry<String, JsonElement> entry : params.getAsJsonObject("names").entrySet()) {
boolean ok;
try {
ok = applyAddressName(parseReaAddress(entry.getKey()), entry.getValue().getAsString());
}
catch (RequestFailure failure) {
ok = false;
}
result.addProperty(entry.getKey(), ok);
}
return result;
}
private JsonArray listDocuments(JsonObject params) {
requireKeys(params, Set.of());
JsonArray result = new JsonArray();
+3 -10
View File
@@ -166,16 +166,9 @@ rea import-reference-source /absolute/path/to/source
```
The import records hashes and metadata for the supplied files, separately
from observations of the current app. It honors the source tree's `.gitignore`
and applies default exclusions for common generated and dependency paths such
as `node_modules/`, `dist/`, and `*.log`. Pattern-based exclusions record the
matched pattern and whether it came from project, default, caller, or sensitive
path policy. Set `REA_REFERENCE_SECRET_PATTERNS_JSON` to a JSON array of ignore
patterns when you want to mark selected paths as sensitive; those patterns are
reported separately as configured-secret exclusions.
Re-import saved graphs whose pattern-based exclusions lack `pattern` before
using them in source-to-bundle comparisons.
from observations of the current app. File names do not automatically exclude
files. Set `REA_REFERENCE_SECRET_PATTERNS_JSON` to a JSON array of ignore
patterns when you want to exclude selected paths.
JavaScript and TypeScript import parsing requires valid UTF-8. Malformed source
bytes retain their original hashes and sizes with a decoding diagnostic; REA
-12
View File
@@ -29,13 +29,6 @@ section names or the record being inside the initial 4 KiB header probe.
Program and section declarations must agree; duplicate, conflicting, truncated
or out-of-file records are rejected. Stripped section tables and section-only
records are supported. Extended table numbering is explicitly unsupported.
For carved ELFs whose section table extends beyond the captured file, REA
examines every complete captured section header and records the unavailable
headers as a limitation. A valid program-header ABI record can still establish
the supported declaration. Available section declarations must agree with it;
their duplicate, conflicting or unreadable records remain errors. A missing
program-header record does not make ABI declarations in uncaptured sections
absent or supply a default ABI.
The field layout follows
[`Elf_MIPS_ABIFlags_v0`](https://github.com/bminor/glibc/blob/master/elf/elf.h).
@@ -99,11 +92,6 @@ observations and does not relabel the upstream result as verified.
CLI/MCP discovery and decompilation, direct calls, target/profile/Evidence
identity, snapshot round-trip and final process cleanup remain covered.
For both byte orders, the lane also carves away the section table while retaining
all program-header payloads. It checks the actual Ghidra language, entry-address
decompilation, distinct artifact digest and missing-section limitations through
CLI Evidence and an MCP-produced snapshot. Caller-selected Ghidra heap limits
are passed to these child workflows.
Pseudocode presence is a liveness check, not proof of semantic equivalence.
Instruction decoding and reader agreement likewise do not establish runtime,
delay-slot execution or complete floating-point semantics. Assertion regressions
+4 -33
View File
@@ -68,15 +68,7 @@ selects the npm release, and persistent MCP registrations are pinned to the
version that performed setup. Installing newer instructions does not update a
running server or its registration.
The npm release checked on **2026-10-10** was **6.3.0**, published from
[`74cf9e14`](https://github.com/morluto/rea/commit/74cf9e1401fcd89482fe39c27cc898f5858e9b72),
with bundled skill version 34. It does not include automatic Pi or Hermes
registration: `setup --client pi` and `setup --client hermes` reject those IDs
before writing configuration. Their setup workflows below require a source build
or a later release containing those integrations; `@latest` alone cannot select
unpublished changes.
The earlier release checked on **2026-10-07** was **5.0.0** (133 MCP tools), published
The release checked on **2026-10-07** was **5.0.0** (133 MCP tools), published
from the fixed checkpoint
[`b33236ec`](https://github.com/morluto/rea/releases/tag/rea-agents-5.0.0).
The public CLI, MCP catalog and target-free session, and isolated update from
@@ -153,13 +145,6 @@ listed after the table because its connector is not one of these files:
For GitHub Copilot CLI 1.0.95, `gpt-4.1` model metadata can block ordinary
chat with REA's full input-schema profile before sending a model request
(`compaction_static_context_blocked`; [#1554](https://github.com/morluto/rea/issues/1554)).
For the native offline OpenAI-compatible BYOK adapter, full-profile chat and
analysis also passed with a distinct `COPILOT_PROVIDER_MODEL_ID` such as
`rea-gpt-4.1`, `COPILOT_PROVIDER_WIRE_MODEL=gpt-4.1`, and that distinct ID selected
through `copilot --model rea-gpt-4.1`. The local fixture requested
`COPILOT_PROVIDER_MAX_PROMPT_TOKENS=1000000`; configure the limit supported by
your backend. This keeps every full schema and the actual wire model intact.
It does not establish the effective client budget or fix the built-in-ID path.
The existing compact profile passed native chat and analysis with the complete
tool inventory on Linux using a loopback model fixture. After setup, add
`"REA_MCP_INPUT_SCHEMA_PROFILE": "compact"` to the `env` object of the
@@ -170,9 +155,6 @@ schema constraints; REA still validates complete canonical inputs. Full-profile
Windows remain unverified; see [native client verification](testing.md).
For [Pi](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/mcp.md),
automatic setup requires a build containing the integration; npm 6.3.0 does not
include it. See [released package and main](#released-package-and-main).
In a supported build,
setup writes a `type: "stdio"` entry under `mcpServers.rea` in the user-level
`~/.pi/agent/mcp.json` and installs the bundled skill under `~/.agents/skills`.
Use `rea setup --client pi --dry-run --json` to inspect the plan, then
@@ -231,10 +213,7 @@ registration. Doctor treats an `enabled: false` entry as active when
`enabledServers` lists `rea`, as OMP does, unless `disabledServers` also lists
it. Run setup under each profile that should load REA.
For Hermes, automatic setup also requires a build containing the integration;
npm 6.3.0 does not include it. See
[released package and main](#released-package-and-main).
In a supported build, setup writes a `mcp_servers.rea` entry to `config.yaml`, preserving
For Hermes, setup writes a `mcp_servers.rea` entry to `config.yaml`, preserving
comments and unrelated settings. It resolves that file from `HERMES_HOME`, else
from the platform default Hermes itself uses — `%LOCALAPPDATA%\hermes` on
Windows, `~/.hermes` elsewhere — including any `HERMES_DATA_DIR_SUFFIX`. Hermes
@@ -367,12 +346,6 @@ Hopper installation or any file write. Declining or pressing Ctrl-C makes no
changes. Agent configuration writes preserve unrelated entries and comments,
create backups, use atomic replacement, and verify their result. Setup and
uninstall retain an existing `.rea.backup` rather than replacing the first snapshot.
Setup also retains valid environment overrides in REA's existing server entry,
such as `REA_MCP_INPUT_SCHEMA_PROFILE` and `REA_MCP_MAX_RESPONSE_BYTES`.
Detected provider settings replace only matching environment keys.
Setup and doctor report a malformed REA environment map or invalid runtime
setting before setup writes files. Repair the named setting in the client
configuration; setup does not silently discard the rest of the map.
After setup, REA reports which agents, analysis tools, and workflow files passed
its final checks. Restart any agent named in the completion message, then begin
@@ -637,10 +610,8 @@ dossiers, instructions, recovered data types, measured load mappings, loaded
memory bytes, and observed file offsets. Independent load-image attestation
supports DOS MZ and explicitly selected COM; PE returns its measurements with that limitation.
On Linux and macOS, `annotate_native_function` also edits a function name and/or
entry comments atomically and returns refreshed analysis, and `set_address_name`
and `set_addresses_names` name a function entry or any other mapped address
(creating or renaming its primary label) with per-address success results. These
session metadata edits leave executable bytes unchanged and are discarded on close. GUI controls
entry comments atomically and returns refreshed analysis. These session metadata
edits leave executable bytes unchanged and are discarded on close. GUI controls
require Hopper; Windows P0 remains read-only.
Windows P0 admits native x86 and x86-64 PE applications and DLLs on fixed local NTFS volumes.
+3 -43
View File
@@ -89,9 +89,9 @@ queries use per-file range indexes, while call sites use exact-range lookups.
Existing node budgets and coverage reporting remain in effect.
Progress identifies the source file being parsed and projected. Cancellation is
checked between files and throughout result transfer. The owned analyzer can
be stopped while its synchronous parser or semantic extractor is active;
the CLI/MCP process remains available for control requests.
checked between files, with event-loop yields that allow notifications and
completed file-local allocations to be released. A single file's synchronous
parser and semantic extraction still need to finish before that boundary.
Graph and Evidence identifiers hash canonical JSON incrementally, without
assembling a single string for the whole graph. The canonical bytes and existing
@@ -113,46 +113,6 @@ smaller view, for example `--format json --filter-output
evidence_id,normalized_result.statistics`. Streaming output does not bound the
memory needed to construct the analysis graph itself.
JavaScript source parsing, static analysis and semantic projection run in one
owned analysis process, reused sequentially across files. Target code is never
executed. The analyzer defaults to 1024 MiB of V8 old-space and a 300000 ms
deadline per source, including startup and fact transfer. Select
`max_heap_mb` and `analysis_timeout_ms` through MCP, or `--max-heap-mb` and
`--analysis-timeout-ms` on the dedicated CLI command. These choices control the
analyzer; the caller's `NODE_OPTIONS` still controls the CLI/MCP process heap.
V8 old-space limits do not impose a process RSS limit.
A source that exhausts the analyzer heap does not terminate the CLI/MCP
process. Completed static facts are retained, other files can still be analyzed,
and unexamined semantic relationships remain explicit unknowns. The parent
also checks transfer expansion and accumulated results against its remaining
heap before accepting semantic facts. A resource-limited result has partial
coverage, the observed limits and an `analyze-javascript-source` unknown scope
with the specific failure, including captured diagnostics when available.
Resource failures do not increment syntax parse failures. There is no fixed
source-length cutoff.
Static observations also need memory when expanded into nodes, relationships
and Evidence. If that expansion does not fit, the file node retains
`static_analysis` and any admitted `semantic_module_analysis` observations,
including their exact values and source locations. Use the public modules item
view to read them. The graph marks those unexpanded relationships as unknown.
If cumulative result capacity is exhausted, analysis stops; inventoried but
unexamined files remain present with explicit unknown scopes.
A timeout stops the remaining analysis and returns typed failure details with
completed partial Evidence. MCP failure details return
`partial_observation: { kind: "retained-evidence", evidence_id: "..." }`
after recording succeeds, so `inspect_analysis_view` can open that analysis
directly without serializing the entire partial graph into the error response.
CLI failure output retains the complete partial Evidence.
Cancellation after source analysis begins likewise
retains completed facts; an SDK client may reject its cancelled request before
receiving that reply. On the same MCP connection, inspect the Evidence bundle
and use the retained analysis ID with `inspect_analysis_view`. Owned analyzer
cleanup is verified before its private files are released. Cleanup uncertainty
is reported separately and retains ownership for retry.
CLI workflows parse larger JSON input files incrementally from one verified
regular-file handle, without constructing a document-sized string. Smaller
files retain native JSON parsing. Both paths require strict JSON and valid
-6
View File
@@ -397,12 +397,6 @@ unpaired Unicode surrogate; a rejection identifies the field and UTF-16 index
and leaves every annotation unchanged. CRLF, supplementary Unicode characters,
and combining characters are preserved. Windows P0 remains read-only. Ghidra has no
GUI authority, and REA never falls back automatically to Hopper.
`set_address_name` and `set_addresses_names` give Ghidra sessions the same
compact naming results as Hopper: a local function entry renames that function,
and any other mapped address, such as a global, receives a new or renamed primary
label. A batch applies each address separately and reports one success boolean
per address. Use them to name many globals and helpers cheaply; use
`annotate_native_function` when you also want comments and a refreshed dossier.
Ghidra name edits preserve the existing namespace. Supply either a leaf name
such as `renamed` or a fully qualified name in that namespace, such as
`alpha::renamed`. The returned qualified name can be reused as an idempotent
+7 -26
View File
@@ -99,10 +99,9 @@ result that its client offloads, and Pi exercises default codemode execution.
Use `REA_VERIFY_RUNTIME_ROOT` to select a production-only installed REA package.
Receipts retain client versions, result digests, host coverage and owned-process
cleanup. These POSIX lanes use a deterministic loopback model, so they do not
prove live model-provider or native Windows compatibility. Qwen, Pi and Hermes
bind both `HOME` and `USERPROFILE` to the disposable account. Qwen and Pi discover
the shared personal skill through their default search paths without an explicit
skill setting; Hermes discovers it through the selected `HERMES_HOME`.
prove live model-provider or native Windows compatibility. Qwen and Pi use
caller-configured skill directories to isolate the fixture account from the OS
home; this does not prove their default home-directory discovery.
Set `REA_VERIFY_HERMES_STICKY_PROFILE=1` to exercise native Hermes selection of
a named sticky profile with `HERMES_HOME` still pointing to its root.
@@ -160,25 +159,8 @@ Use `-- chat` for ordinary
chat or `REA_VERIFY_RUNTIME_ROOT` for a production-only installed package.
The native offline BYOK adapter uses a loopback OpenAI completions/SSE fixture
and `gpt-5.4` model metadata; model inference and token usage are synthetic.
Set `REA_VERIFY_COPILOT_MODEL` to examine another client model ID and
`REA_VERIFY_COPILOT_WIRE_MODEL` for its backend model name (defaults to the client
ID). Every actual HTTP request's model is checked and recorded separately.
Both `HOME` and `USERPROFILE` point to the disposable account; native `skill add`
still selects the installed skill directory explicitly.
The same native client passed full-profile chat and analysis with the actual
wire model `gpt-4.1` under a distinct BYOK model ID:
```bash
REA_VERIFY_COPILOT_MODEL=rea-gpt-4.1 REA_VERIFY_COPILOT_WIRE_MODEL=gpt-4.1 npm run verify:copilot-client -- chat
REA_VERIFY_COPILOT_MODEL=rea-gpt-4.1 REA_VERIFY_COPILOT_WIRE_MODEL=gpt-4.1 npm run verify:copilot-client -- call
```
These runs retain full canonical input/output schemas, all tools, installed-skill
loading and complete Evidence readback. They use the fixture's requested
one-million-token BYOK prompt setting; effective capacity and live API acceptance
remain unknown. With the built-in `gpt-4.1` model ID, the verified client still
blocks the full input-schema profile before HTTP with
Set `REA_VERIFY_COPILOT_MODEL` to examine another model configuration. In the
verified client, `gpt-4.1` blocks the full input-schema profile before HTTP with
`compaction_static_context_blocked`, even when requesting a larger BYOK prompt
capacity. The effective capacity is unknown. The default verifier preserves
the complete catalog and full schemas. To verify the existing compact profile:
@@ -261,9 +243,8 @@ unverified; skill discovery uses an explicit isolated custom directory.
verified with `@deepseek-ai/dsh@0.2.0-rc.2`) and Git. Set
`REA_VERIFY_DEEPSEEK_COMMAND` to select its executable. This optional POSIX lane
installs the skill through `rea setup --skill`, writes the native Cordis MCP
patch into an isolated `DSH_HOME`, and binds `HOME` and `USERPROFILE` to the
disposable account. The native default `~/.agents/skills` search path discovers
the installed skill without a `DSH_AGENTS_HOME` override. A separate Git root prevents inherited project skills from
patch into an isolated `DSH_HOME`, and uses `DSH_AGENTS_HOME` for native personal
skill discovery. A separate Git root prevents inherited project skills from
masking a missing installation. The default `call` mode checks skill loading,
complete catalog discovery, the actual forwarded input schemas and regexes,
and full JavaScript Evidence for a Unicode path. Use `-- chat` for ordinary
+4 -7
View File
@@ -85,22 +85,19 @@ if [[ "$version" =~ \+ ]]; then
fail "npm cannot install an exact version with build metadata. Pass a version without build metadata, then retry."
fi
install_args=(install --global)
prefix_args=()
if [[ "$platform" == "Linux" ]]; then
install_args+=(--prefix "$HOME/.local")
prefix_args=(--prefix "$HOME/.local")
install_bin="$HOME/.local/bin/rea"
else
npm_prefix="$(npm prefix --global)" || fail "the npm global prefix could not be read. Repair the npm configuration, then retry."
install_bin="$npm_prefix/bin/rea"
fi
install_args+=("$PACKAGE@$version")
printf 'REA install plan\n'
printf ' Version: %s\n' "$version"
printf ' Runtime: Node.js %s\n' "$node_version"
printf ' Command:'
printf ' %q' npm "${install_args[@]}"
printf '\n'
printf ' Command: npm install --global %s@%s\n' "$PACKAGE" "$version"
printf ' Binary: %s\n' "$install_bin"
printf ' Setup: %s\n' "$([[ "$start_setup" == true ]] && printf 'start when a terminal is available' || printf 'skipped')"
@@ -110,7 +107,7 @@ if [[ "$dry_run" == true ]]; then
fi
printf 'Installing %s@%s...\n' "$PACKAGE" "$version"
npm "${install_args[@]}" || fail "npm could not install REA. Check registry access and npm permissions, then retry."
npm install --global ${prefix_args[@]+"${prefix_args[@]}"} "$PACKAGE@$version" || fail "npm could not install REA. Check registry access and npm permissions, then retry."
[[ -x "$install_bin" ]] || fail "npm completed without installing the rea command. Check the npm global bin directory and PATH, then retry."
installed_version="$("$install_bin" --version 2>/dev/null | tr -d '[:space:]')" || fail "the installed REA version could not be read. Reinstall the requested version, then retry."
[[ "$installed_version" == "$version" ]] || fail "installed version $installed_version does not match $version. Reinstall the requested version, then retry."
-1
View File
@@ -3,7 +3,6 @@
"entry": [
"src/main.ts",
"src/cli.ts",
"src/composition/javascriptAnalysisWorkerProcess.ts",
"src/contracts/errorSchemas.ts",
"src/evaluation/AgentEvaluationFixtures.ts",
"src/application/RealHopperAssertions.ts",
-3
View File
@@ -30,9 +30,6 @@
"access": "public"
},
"type": "module",
"imports": {
"#javascript-analysis-worker": "./dist/composition/javascriptAnalysisWorkerProcess.js"
},
"bin": {
"rea": "scripts/rea.mjs",
"rea-agents": "scripts/rea.mjs"
@@ -1,28 +0,0 @@
import { analyzeJavaScriptApplication } from "../../dist/application/javascript/JavaScriptApplicationService.js";
import { ArtifactResourceScope } from "../../dist/artifacts/ArtifactResourceScope.js";
/** Analyze one JavaScript application and close its caller-owned resources. */
export const analyzeJavaScriptApplicationWithOwnedScope = async (input) => {
const scope = new ArtifactResourceScope();
let outcome;
try {
const result = await analyzeJavaScriptApplication(input, scope);
outcome = result.ok
? { kind: "completed", value: result.value }
: { kind: "failed", cause: result.error };
} catch (cause) {
outcome = { kind: "failed", cause };
}
try {
await scope.close();
} catch (cleanupCause) {
if (outcome.kind === "failed")
throw new AggregateError(
[outcome.cause, cleanupCause],
"JavaScript analysis and artifact cleanup both failed",
);
throw cleanupCause;
}
if (outcome.kind === "failed") throw outcome.cause;
return outcome.value;
};
+4 -22
View File
@@ -21,6 +21,7 @@ export async function verifyGhidraEntryAliases({
new URL("../../tests/conformance/ghidra/entry-aliases.c", import.meta.url),
);
const path = join(workspace, "entry-aliases");
const prefix = process.platform === "darwin" ? "_" : "";
try {
await exec(compiler, ["-O0", "-g", "-fno-inline", source, "-o", path], {
env,
@@ -28,8 +29,7 @@ export async function verifyGhidraEntryAliases({
});
const bytes = await readFile(path);
await call("close_binary");
const imported = await call("open_binary", { path, provider_id: "ghidra" });
const prefix = imported.format === "mach-o" ? "_" : "";
await call("open_binary", { path, provider_id: "ghidra" });
const names = await call("list_names");
const alias = names.find(
({ value }) => value === `${prefix}rea_entry_alias`,
@@ -46,10 +46,8 @@ export async function verifyGhidraEntryAliases({
);
assert.ok(canonical, "Fixture alias is not at a function entry");
const xrefsSelectors = [];
// CLI xrefs keeps bare hexadecimal selectors as addresses. A Mach-O
// primary label such as "dead" is tested below as a procedure name instead.
for (const value of [
`${prefix}rea_alias_target`,
canonical.value,
alias.value,
`${prefix}rea_xrefs_data`,
`${prefix}rea_xrefs_unreferenced`,
@@ -91,18 +89,6 @@ export async function verifyGhidraEntryAliases({
);
assert.ok(interior);
assert.notEqual(interior.address, alias.address);
assert.equal(
interior.symbol.type,
"label",
"Fixture interior control must remain an imported label",
);
assert.equal(
(await call("list_procedures")).some(
({ address }) => address === interior.address,
),
false,
"Fixture interior control must not be a Ghidra procedure entry",
);
const failure = await reject("procedure_address", {
procedure: interior.value,
});
@@ -167,11 +153,7 @@ export async function verifyGhidraEntryAliases({
{ env, timeout: 240000, maxBuffer: 16 * 1024 * 1024 },
);
const evidence = JSON.parse(stdout);
assert.deepEqual(
evidence.normalized_result,
expected,
`CLI xrefs mismatch for ${JSON.stringify(selector)}`,
);
assert.deepEqual(evidence.normalized_result, expected);
assert.equal(evidence.parameters.address, selector.at(-1));
}
}
@@ -54,14 +54,6 @@ export async function verifyGhidraNamespaceAnnotations({
);
return { namespace, address: procedure.address };
});
const names = await call("list_names");
const globals = ["alpha", "outer::inner"].map((namespace) => {
const symbol = names.find(
(item) => item.value === `${namespace}::value` && item.symbol.primary,
);
assert.ok(symbol, `Missing demangled fixture global ${namespace}::value`);
return { namespace, address: symbol.address };
});
const ambiguous = await reject("procedure_address", { procedure: "same" });
assert.equal(ambiguous.code, "invalid_request");
for (const { address } of entries)
@@ -133,16 +125,6 @@ export async function verifyGhidraNamespaceAnnotations({
});
assert.deepEqual(unchanged.annotations, qualified.annotations);
}
await verifyAddressNames(call, [entries[0], entries[2], ...globals]);
for (const { namespace, address } of entries) {
assert.equal(
await call("set_address_name", {
address,
name: `${namespace}::qualified`,
}),
true,
);
}
const { stdout } = await exec(
process.execPath,
[
@@ -177,96 +159,6 @@ export async function verifyGhidraNamespaceAnnotations({
}
}
async function verifyAddressNames(call, symbols) {
for (const { namespace, address } of symbols) {
assert.equal(
await call("set_address_name", { address, name: "address_renamed" }),
true,
);
const qualified = `${namespace}::address_qualified`;
assert.equal(
await call("set_address_name", { address, name: qualified }),
true,
);
assert.equal(await call("address_name", { address }), qualified);
assert.equal(
await call("set_address_name", { address, name: "other::literal" }),
true,
);
const literal = await call("address_name", { address });
assert.equal(literal, `${namespace}::other::literal`);
assert.equal(
await call("set_address_name", { address, name: literal }),
true,
);
assert.equal(await call("address_name", { address }), literal);
assert.equal(
await call("set_address_name", { address, name: qualified }),
true,
);
for (let repeat = 0; repeat < 2; repeat++) {
const readback = await call("address_name", { address });
assert.deepEqual(
await call("set_addresses_names", { names: { [address]: readback } }),
{ [address]: true },
);
assert.equal(await call("address_name", { address }), qualified);
}
assert.equal(
await call("set_address_name", { address, name: `${namespace}::` }),
false,
);
const session = await call("binary_session");
for (const operation of [
"set_address_name",
"set_addresses_names",
"address_name",
"list_names",
])
assert.equal(
session.capabilities.find((item) => item.operation === operation)
?.available,
true,
`An invalid name must not mark ${operation} unavailable`,
);
assert.equal(await call("address_name", { address }), qualified);
}
const [valid, invalid] = symbols;
assert.deepEqual(
await call("set_addresses_names", {
names: {
[valid.address]: `${valid.namespace}::batch_renamed`,
[invalid.address]: `${invalid.namespace}::`,
},
}),
{ [valid.address]: true, [invalid.address]: false },
);
assert.equal(
await call("address_name", { address: valid.address }),
`${valid.namespace}::batch_renamed`,
);
assert.equal(
await call("address_name", { address: invalid.address }),
`${invalid.namespace}::address_qualified`,
);
const names = await call("list_names");
for (const { namespace, address } of symbols) {
const expected =
address === valid.address
? `${namespace}::batch_renamed`
: `${namespace}::address_qualified`;
assert.ok(
names.some(
(item) =>
item.address === address &&
item.value === expected &&
item.symbol.primary,
),
`Missing refreshed primary symbol ${expected}`,
);
}
}
async function requireNamespaceDemangler(env) {
const inspection = inspectGhidraInstallation({
environment: process.env,
+2 -13
View File
@@ -22,7 +22,6 @@ const runtimeRoot = process.env.REA_VERIFY_RUNTIME_ROOT ?? repo;
const command = process.env.REA_VERIFY_COPILOT_COMMAND ?? "copilot";
const mode = process.argv[2] ?? "call";
const model = process.env.REA_VERIFY_COPILOT_MODEL ?? "gpt-5.4";
const wireModel = process.env.REA_VERIFY_COPILOT_WIRE_MODEL ?? model;
const inputSchemaProfile =
process.env.REA_VERIFY_COPILOT_SCHEMA_PROFILE ?? "full";
assert(
@@ -51,7 +50,6 @@ await exec("git", ["init", "--quiet", workspace], { timeout: 30_000 });
const environment = {
PATH: process.env.PATH,
NODE_OPTIONS: process.env.NODE_OPTIONS,
HOME: account,
USERPROFILE: account,
COPILOT_HOME: profile,
COPILOT_OFFLINE: "true",
@@ -62,7 +60,7 @@ const environment = {
COPILOT_PROVIDER_BEARER_TOKEN: "",
COPILOT_PROVIDER_HEADERS: "",
COPILOT_PROVIDER_MODEL_ID: model,
COPILOT_PROVIDER_WIRE_MODEL: wireModel,
COPILOT_PROVIDER_WIRE_MODEL: model,
COPILOT_PROVIDER_MAX_PROMPT_TOKENS: "1000000",
COPILOT_PROVIDER_MAX_OUTPUT_TOKENS: "4096",
REA_PROCESS_RUN_ID: verifier.run_id,
@@ -120,17 +118,10 @@ const extractEvidence = (value) => {
}
return undefined;
};
const wireModels = [];
const fixture = await createOpenAiModelFixture({
directory: lab,
prefix: "copilot",
onRequest: async ({ body, tools, requestIndex }) => {
assert.equal(
body.model,
wireModel,
"Copilot must send the selected wire model",
);
wireModels.push(body.model);
// Auxiliary requests without tools cannot execute the analyst's workflow.
if (tools.length === 0)
return { role: "assistant", content: "REA fixture title" };
@@ -433,7 +424,6 @@ try {
clientVersion,
mode,
model,
wireModel,
inputSchemaProfile,
passed: failure === undefined,
artifacts: lab,
@@ -450,7 +440,7 @@ try {
capacityBoundary:
inputSchemaProfile === "compact"
? "Explicit compact profile: complete inventory and canonical server validation; advertised schemas may be reduced. This does not fix the full-profile gpt-4.1 context boundary."
: "Complete canonical input and output schemas. Client model ID and wire model are recorded separately; effective token capacity and live provider compatibility remain unknown.",
: "gpt-4.1 model configuration blocks the full catalog before HTTP even with a ten-million-token requested prompt override; gpt-5.4 is the verified full-profile local fixture configuration",
catalogSize,
schemasChecked,
spillReadRequested,
@@ -458,7 +448,6 @@ try {
skillLoaded,
artifactDigest,
finalSeen,
wireModels,
requests: fixture.requests,
probes: fixture.probes,
fixtureFailure: fixture.failure,
+2 -2
View File
@@ -40,9 +40,9 @@ await Promise.all([
]);
const environment = {
PATH: process.env.PATH ?? "",
HOME: account,
USERPROFILE: account,
DSH_HOME: profile,
DSH_AGENTS_HOME: join(account, ".agents"),
OPENAI_API_KEY: "local-fixture-key",
REA_PROCESS_RUN_ID: verifier.run_id,
};
@@ -328,7 +328,7 @@ try {
"loopback custom OpenAI-compatible adapter; no live DeepSeek provider claim",
modelContextWindow: 1000000,
skillDiscovery:
"native HOME shared personal directory; isolated project root",
"native DSH_AGENTS_HOME personal directory; isolated project root",
catalogSize: catalog?.length,
patternCount,
uniquePatterns: patterns.size,
+8 -2
View File
@@ -54,7 +54,6 @@ await writeFile(
);
const environment = {
PATH: process.env.PATH ?? "",
HOME: account,
USERPROFILE: account,
[client === "pi" ? "PI_CODING_AGENT_DIR" : "HERMES_HOME"]: profile,
PI_OFFLINE: "1",
@@ -72,6 +71,13 @@ const original =
})
: "# Keep caller settings.\nmcp_servers:\n other:\n command: unrelated-server\n enabled: false\n";
await writeFile(configPath, original);
if (client === "pi") {
// The CLI fixture account and native os.homedir() differ; use Pi's caller-owned skill setting.
await writeFile(
join(profile, "settings.json"),
JSON.stringify({ skills: [join(account, ".agents", "skills")] }),
);
}
const clientVersion = (
await exec(command, ["--version"], { env: environment, timeout: 30_000 })
).stdout.trim();
@@ -442,7 +448,7 @@ try {
"loopback deterministic OpenAI-compatible endpoint; no live provider claim",
skillDiscovery:
client === "pi"
? "native HOME shared personal directory; no explicit skill setting"
? "caller-configured isolated shared directory; default OS home discovery unverified"
: "native HERMES_HOME personal directory",
stickyHermes,
catalogSize: catalog?.length,
+5 -3
View File
@@ -45,7 +45,6 @@ await Promise.all([
]);
const baseEnvironment = {
PATH: process.env.PATH ?? "",
HOME: account,
USERPROFILE: account,
QWEN_HOME: profile,
QWEN_RUNTIME_DIR: runtime,
@@ -72,6 +71,9 @@ const original = JSON.stringify(
},
telemetry: { enabled: false },
model: { name: "rea-client-fixture" },
// Qwen uses os.homedir(), while REA's isolated CLI account uses USERPROFILE.
// This caller-owned setting lets the real client load the REA-installed bundle.
skills: { directories: [sharedSkills] },
mcpServers: { other: { command: "unrelated-server", disabled: true } },
},
null,
@@ -110,7 +112,7 @@ const configured = JSON.parse(
await readFile(join(profile, "settings.json"), "utf8"),
);
assert.deepEqual(configured.model, { name: "rea-client-fixture" });
assert.equal(configured.skills, undefined);
assert.deepEqual(configured.skills, { directories: [sharedSkills] });
assert.deepEqual(configured.mcpServers.other, {
command: "unrelated-server",
disabled: true,
@@ -382,7 +384,7 @@ try {
modelFixture:
"loopback deterministic OpenAI-compatible endpoint; no live model-provider claim",
skillDiscovery:
"native HOME shared personal directory; no explicit skill setting",
"caller-configured isolated shared directory; default OS home discovery unverified",
catalogSize: TOOL_CONTRACTS.length,
requests: fixture.requests,
probes: fixture.probes,
+1 -109
View File
@@ -2,7 +2,7 @@
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 { mkdtemp, mkdir, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -60,9 +60,6 @@ const env = {
JAVA_HOME: installation.javaHome,
HOPPER_LAUNCHER_PATH: "/rea-unconfigured-deep-provider/hopper",
};
for (const setting of ["GHIDRA_HEADLESS_MAXMEM", "GHIDRA_MAXMEM"]) {
if (process.env[setting] !== undefined) env[setting] = process.env[setting];
}
const reports = [];
let primaryFailure;
try {
@@ -230,103 +227,6 @@ try {
fixture.sha256,
"Analysis modified the source executable",
);
// Carved firmware keeps all program headers/load bytes but loses sections.
const read16 = (offset) =>
byteOrder === "little"
? sourceBytes.readUInt16LE(offset)
: sourceBytes.readUInt16BE(offset);
const read32 = (offset) =>
byteOrder === "little"
? sourceBytes.readUInt32LE(offset)
: sourceBytes.readUInt32BE(offset);
const sectionOffset = read32(32);
const cut = sectionOffset - 1;
const programOffset = read32(28);
const programCount = read16(44);
assert.equal(read16(42), 32);
assert.ok(cut >= programOffset + programCount * 32);
for (let i = 0; i < programCount; i += 1) {
const offset = programOffset + i * 32;
assert.ok(read32(offset + 4) + read32(offset + 16) <= cut);
}
const carvedBytes = sourceBytes.subarray(0, cut);
const carvedPath = join(workspace, `${byteOrder}-carved.elf`);
const carvedSha256 = createHash("sha256")
.update(carvedBytes)
.digest("hex");
await writeFile(carvedPath, carvedBytes);
const carvedResolved = await parseBinaryTarget(carvedPath);
if (!carvedResolved.ok) throw carvedResolved.error;
assert.deepEqual(
carvedResolved.value.mips.abiFlags,
independent.mips.abiFlags,
);
assert.match(
carvedResolved.value.mips.limitations.join(" "),
/section header table/u,
);
const carvedTarget = await call("open_binary", {
path: carvedPath,
provider_id: "ghidra",
});
assert.equal(carvedTarget.sha256, carvedSha256);
const carvedImage = await call("inspect_native_load_image");
assertMipsLoadedImage(carvedImage.observations, byteOrder, carvedSha256);
const carvedProcedures = await call("list_procedures");
assert.ok(
carvedProcedures.some(
(p) =>
BigInt(p.address) === BigInt(independent.symbols.rea_mips_entry),
),
);
const carvedDossier = functionDossierSchema.parse(
await call("analyze_function", {
procedure: independent.symbols.rea_mips_entry,
}),
);
assert.ok(carvedDossier.pseudocode.trim().length > 0);
const carvedSnapshotPath = join(
workspace,
`${byteOrder}-carved.snapshot.json`,
);
await call("close_binary", { snapshot_path: carvedSnapshotPath });
const carvedSnapshot = parseAnalysisSnapshot(
JSON.parse(await readFile(carvedSnapshotPath, "utf8")),
);
assert.equal(carvedSnapshot.target.sha256, carvedSha256);
assert.ok(
carvedSnapshot.evidence_bundle.records.some((record) =>
parseEvidence(record).limitations.some((item) =>
item.includes("section header table"),
),
),
);
const carvedCli = await execute(
process.execPath,
[
entrypoint,
"function",
carvedPath,
independent.symbols.rea_mips_entry,
"--provider",
"ghidra",
"--json",
],
{ env, timeout: 240000, maxBuffer: 16 * 1024 * 1024 },
);
const carvedEvidence = parseEvidence(JSON.parse(carvedCli.stdout));
assert.equal(carvedEvidence.subject?.digest.sha256, carvedSha256);
assert.ok(
carvedEvidence.limitations.some((item) =>
item.includes("section header table"),
),
);
assert.equal(
functionDossierSchema.parse(carvedEvidence.normalized_result).procedure
.address,
carvedDossier.procedure.address,
);
assert.deepEqual(await readFile(carvedPath), carvedBytes);
reports.push({
...fixture,
independent_reader: independent,
@@ -341,14 +241,6 @@ try {
"CLI/MCP and snapshot identity",
],
procedures: procedures.length,
carved: {
sha256: carvedSha256,
source_bytes: carvedBytes.length,
section_header_offset: sectionOffset,
effective_language: carvedImage.observations.language_id,
limitations: carvedResolved.value.mips.limitations,
procedures: carvedProcedures.length,
},
status: "passed",
});
} catch (cause) {
@@ -3,7 +3,7 @@
import { realpath } from "node:fs/promises";
import { parseArgs } from "node:util";
import { analyzeJavaScriptApplicationWithOwnedScope } from "../../lib/javascript-application-analysis.mjs";
import { analyzeJavaScriptApplication } from "../../../dist/application/javascript/JavaScriptApplicationService.js";
import {
compareApplicationVersionsEvidence,
compareJavaScriptExportShapesEvidence,
@@ -199,5 +199,9 @@ function selectorKey(selector) {
}
async function analyze(path) {
return analyzeJavaScriptApplicationWithOwnedScope({ input_path: path });
const result = await analyzeJavaScriptApplication({
input_path: path,
});
if (!result.ok) throw result.error;
return result.value;
}
@@ -3,8 +3,8 @@
import { readFile, realpath } from "node:fs/promises";
import { parseArgs } from "node:util";
import { analyzeJavaScriptApplication } from "../../../dist/application/javascript/JavaScriptApplicationService.js";
import { reconcileJavaScriptRuntimeEvidence } from "../../../dist/application/javascript/JavaScriptRuntimeReconciliationService.js";
import { analyzeJavaScriptApplicationWithOwnedScope } from "../../lib/javascript-application-analysis.mjs";
import {
completeVerifierRun,
createVerifierRun,
@@ -44,13 +44,14 @@ const canonicalLayers = await Promise.all(
);
const staticLayers = [];
for (const layer of canonicalLayers) {
const analyzed = await analyzeJavaScriptApplicationWithOwnedScope({
const analyzed = await analyzeJavaScriptApplication({
input_path: layer.path,
format: "auto",
});
if (!analyzed.ok) throw analyzed.error;
staticLayers.push({
role: layer.role,
analysis: analyzed,
analysis: analyzed.value,
runtime_mappings: [],
});
}
+1 -7
View File
@@ -373,13 +373,7 @@ const readExecutableMetadata = async (
if (!abiFlags.ok) return abiFlags;
return ok({
...parsed.value,
mips: {
...parsed.value.mips,
abiFlags: abiFlags.value.abiFlags,
...(abiFlags.value.limitations.length === 0
? {}
: { limitations: abiFlags.value.limitations }),
},
mips: { ...parsed.value.mips, abiFlags: abiFlags.value },
});
};
+2 -19
View File
@@ -1,22 +1,17 @@
import { err, ok, type Result } from "../domain/result.js";
import {
RegularFileCleanupFailure,
readRegularFileText,
} from "./RegularFileRead.js";
import { readRegularFileText } from "./RegularFileRead.js";
import {
effectiveClientServer,
parseClientConfiguration,
type ClientConfigurationDocument,
} from "./ClientConfigurationDocument.js";
import type { SetupClient } from "./SupportedClients.js";
import { clientRegistrationEnvironment } from "./ClientRegistrationEnvironment.js";
/** A named source failure that setup can explain without losing the bad path. */
export interface ClientConfigurationFileError {
readonly kind: "unreadable" | "malformed";
readonly path: string;
readonly detail: string;
readonly cleanupFailure?: RegularFileCleanupFailure;
}
/** Preserve named read failures and distinguish a missing source from an empty file. */
@@ -32,9 +27,6 @@ export const readConfigurationText = async (
kind: "unreadable",
path,
detail: `Configuration ${path} could not be read: ${cause instanceof Error ? cause.message : String(cause)}`,
...(cause instanceof RegularFileCleanupFailure
? { cleanupFailure: cause }
: {}),
});
}
};
@@ -71,16 +63,7 @@ export const readClientConfigurationFiles = async (
for (const path of client.configPaths ?? [client.configPath]) {
const document = await readConfigurationFile(path, client.format);
if (!document.ok) return document;
if (document.value !== undefined) {
const environment = clientRegistrationEnvironment(document.value);
if (!environment.ok)
return err({
kind: "malformed",
path,
detail: `Configuration ${path} has an invalid REA server environment: ${environment.error.settings.map(({ setting, constraint }) => `${setting}: ${constraint}`).join("; ")}. Repair it before rerunning setup.`,
});
documents.push(document.value);
}
if (document.value !== undefined) documents.push(document.value);
}
return ok(documents);
};
@@ -1,54 +0,0 @@
import { z } from "zod";
import { parseEnvironment } from "../config/environment.js";
import { ConfigurationError } from "../domain/configurationErrors.js";
import { err, ok, type Result } from "../domain/result.js";
import {
effectiveClientServer,
type ClientConfigurationDocument,
} from "./ClientConfigurationDocument.js";
import { PRODUCT_IDENTITY } from "../identity.js";
/** Read explicit REA overrides without dropping peers when one value is invalid. */
export const clientRegistrationEnvironment = (
parsed: ClientConfigurationDocument | undefined,
overrides: Readonly<Record<string, string>> = {},
): Result<Readonly<Record<string, string>>, ConfigurationError> => {
const key =
parsed?.dialect === "opencode" || parsed?.dialect === "opencode_v2"
? "environment"
: "env";
const registration =
parsed === undefined
? undefined
: effectiveClientServer(parsed, PRODUCT_IDENTITY.mcpServerKey);
const raw =
typeof registration === "object" && registration !== null
? Reflect.get(registration, key)
: undefined;
const existing = z
.record(z.string(), z.string())
.safeParse(raw === undefined ? {} : raw);
if (!existing.success)
return err(
new ConfigurationError("Invalid REA server environment", {
settings: existing.error.issues.map((issue) => ({
setting: [key, ...issue.path].join("."),
constraint:
"Server environment must be an object containing only string values",
})),
}),
);
// Validate known settings with the runtime's parser, but retain the original
// string overrides, including unknown client-specific keys and no defaults.
const environment = { ...existing.data, ...overrides };
const validated = parseEnvironment(environment);
if (!validated.ok) return validated;
return ok(
Object.fromEntries(
Object.entries(environment).sort(([left], [right]) =>
left.localeCompare(right),
),
),
);
};
+6 -27
View File
@@ -5,12 +5,6 @@ import type {
} from "../domain/binaryTargetTypes.js";
import { err, ok, type Result } from "../domain/result.js";
/** Observed ABI declarations and coverage of their source tables. */
export interface MipsAbiFlagsInspection {
readonly abiFlags: MipsAbiFlags | null;
readonly limitations: readonly string[];
}
/**
* Read ELF32 MIPS ABI declarations from the caller's already-open file.
* Inspect both typed tables (not section names), including records beyond the
@@ -21,7 +15,7 @@ export const readMipsElfAbiFlags = async (
handle: FileHandle,
metadata: MipsElfMetadata,
checkCancelled: () => void,
): Promise<Result<MipsAbiFlagsInspection, string>> => {
): Promise<Result<MipsAbiFlags | null, string>> => {
checkCancelled();
if (metadata.elfClass !== 32)
return err("MIPS ABI record inspection currently supports ELF32 only");
@@ -87,7 +81,6 @@ export const readMipsElfAbiFlags = async (
dataOffset: 4,
sizeOffset: 16,
recordType: 0x70000003, // PT_MIPS_ABIFLAGS
optional: false,
},
{
label: "section header table",
@@ -99,7 +92,6 @@ export const readMipsElfAbiFlags = async (
dataOffset: 16,
sizeOffset: 20,
recordType: 0x7000002a, // SHT_MIPS_ABIFLAGS
optional: true,
},
];
// Extended numbering needs a separate section-zero reader. Refuse it rather
@@ -107,7 +99,6 @@ export const readMipsElfAbiFlags = async (
if (u16(bytes, 44) === 0xffff || u16(bytes, 48) >= 0xff00)
return err("extended or reserved MIPS ELF table numbering is unsupported");
let record: Buffer | undefined;
const limitations: string[] = [];
for (const table of tables) {
if (table.count === 0) {
if (table.offset !== 0)
@@ -116,27 +107,16 @@ export const readMipsElfAbiFlags = async (
}
if (table.offset < 52 || table.stride !== table.entrySize)
return err(`invalid MIPS ${table.label} offset or entry size`);
const count = table.optional
? Math.min(
table.count,
Math.max(0, Math.floor((fileSize - table.offset) / table.entrySize)),
)
: table.count;
if (count < table.count)
limitations.push(
`MIPS ${table.label} at file offset ${table.offset} extends beyond the captured file: examined ${count} of ${table.count} complete headers. ABI declarations in unavailable headers remain unknown.`,
);
if (count === 0) continue;
// Counts are bounded by the ELF16 fields and strides by their exact ELF32
// structure sizes. Never allocate according to an untrusted section size.
const contents = await read(
table.offset,
count * table.entrySize,
table.count * table.entrySize,
table.label,
);
if (!contents.ok) return contents;
let found = false;
for (let i = 0; i < count; i += 1) {
for (let i = 0; i < table.count; i += 1) {
checkCancelled();
const position = i * table.entrySize;
if (u32(contents.value, position + table.typeOffset) !== table.recordType)
@@ -154,10 +134,10 @@ export const readMipsElfAbiFlags = async (
record = candidate.value;
}
}
if (record === undefined) return ok({ abiFlags: null, limitations });
if (record === undefined) return ok(null);
// Preserve declarations verbatim, including unknown versions/values. Provider
// admission, not parsing, decides which interpretations have been verified.
const abiFlags: MipsAbiFlags = {
return ok({
version: u16(record, 0),
isaLevel: record.readUInt8(2),
isaRevision: record.readUInt8(3),
@@ -169,6 +149,5 @@ export const readMipsElfAbiFlags = async (
ases: u32(record, 12),
flags1: u32(record, 16),
flags2: u32(record, 20),
};
return ok({ abiFlags, limitations });
});
};
+28 -121
View File
@@ -8,24 +8,14 @@ import {
type HistoricalSourceGraphInput,
} from "../domain/referenceSourceGraph.js";
import { err, ok, type Result } from "../domain/result.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import type { AnalysisCleanupObservation } from "../domain/analysisErrorBase.js";
import { readReferenceSource } from "../reference/ReferenceSourceReader.js";
import type {
ReferenceSourceEntryKind,
ReferenceSourceRead,
ReferenceSourceReaderError,
} from "../reference/ReferenceSourceReaderTypes.js";
import { parseReferenceSourceEntries } from "./ReferenceSourceImportEntries.js";
import { readReferenceSourceVcs } from "./ReferenceSourceVcsAdapter.js";
import {
type ReferenceSourceImportError,
type ReferenceSourceImportOptions,
} from "./ReferenceSourceImportTypes.js";
import {
prepareReferenceSourceImport,
type PreparedReferenceSourceImport,
} from "./ReferenceSourceImportPolicy.js";
import { prepareReferenceSourceImport } from "./ReferenceSourceImportPolicy.js";
const failure = (
code: ReferenceSourceImportError["code"],
@@ -36,12 +26,8 @@ const failure = (
message,
});
const cancelled = (
partial?: ReferenceSourceRead,
): ReferenceSourceImportError => ({
...failure("cancelled", "Reference source import cancelled"),
...(partial === undefined ? {} : { partial }),
});
const cancelled = (): ReferenceSourceImportError =>
failure("cancelled", "Reference source import cancelled");
const isAborted = (signal?: AbortSignal): boolean => signal?.aborted === true;
@@ -129,48 +115,9 @@ const sortExclusions = (
[...exclusions].sort((left, right) => {
const byPath = compareUnicodeCodePoints(left.path, right.path);
if (byPath !== 0) return byPath;
const byReason = compareUnicodeCodePoints(left.reason, right.reason);
if (byReason !== 0) return byReason;
return compareUnicodeCodePoints(
"pattern" in left ? left.pattern : "",
"pattern" in right ? right.pattern : "",
);
return compareUnicodeCodePoints(left.reason, right.reason);
});
const createShouldExclude =
(
exclusions: HistoricalSourceGraphInput["exclusions"],
secrets: PreparedReferenceSourceImport["secrets"],
ignored: PreparedReferenceSourceImport["ignored"],
): ((path: string, kind: ReferenceSourceEntryKind) => boolean) =>
(path, kind) => {
const patternPath = kind === "directory" ? `${path}/` : path;
const secretMatch = secrets.test(patternPath);
if (secretMatch.ignored) {
if (!secretMatch.rule)
throw new Error(`Ignored secret path has no matching rule: ${path}`);
exclusions.push({
path,
reason: "configured-secret",
pattern: secretMatch.rule.pattern,
});
return true;
}
const match = ignored.test(patternPath);
if (!match.ignored) return false;
if (!match.rule)
throw new Error(`Ignored path has no matching rule: ${path}`);
const reason = match.rule.mark;
if (
reason !== "project-ignored" &&
reason !== "default-ignored" &&
reason !== "caller-excluded"
)
throw new Error(`Ignored path has unknown rule origin: ${path}`);
exclusions.push({ path, reason, pattern: match.rule.pattern });
return true;
};
/**
* Import a reference source directory into a committed historical source graph.
*
@@ -180,41 +127,43 @@ const createShouldExclude =
*/
export const importReferenceSource = async (
options: ReferenceSourceImportOptions,
resources: ArtifactResourceScope,
): Promise<Result<HistoricalSourceGraph, ReferenceSourceImportError>> => {
if (isAborted(options.signal)) return err(cancelled());
const prepared = await prepareReferenceSourceImport(options, resources);
const prepared = await prepareReferenceSourceImport(options);
if (!prepared.ok) return prepared;
const { ignored, root, secrets } = prepared.value;
if (isAborted(options.signal)) return err(cancelled());
const exclusions: HistoricalSourceGraphInput["exclusions"] = [];
const shouldExclude = createShouldExclude(exclusions, secrets, ignored);
const shouldExclude = (path: string): boolean => {
if (secrets.ignores(path)) {
exclusions.push({ path, reason: "configured-secret" });
return true;
}
if (ignored.ignores(path)) {
exclusions.push({ path, reason: "caller-excluded" });
return true;
}
return false;
};
const [readResult, vcsResult] = await Promise.all([
readReferenceSource(root, resources, {
const [readResult, vcs] = await Promise.all([
readReferenceSource(root, {
...(options.signal === undefined ? {} : { signal: options.signal }),
shouldExclude,
}),
readReferenceSourceVcs(root, resources, options.signal),
readReferenceSourceVcs(root, options.signal),
]);
if (!readResult.ok)
return err(
combineReadFailures(
readResult.error,
vcsResult.ok ? undefined : vcsResult.error,
readResult.error.partial,
),
);
if (!vcsResult.ok)
return err(
combineReadFailures(vcsResult.error, undefined, readResult.value),
);
if (!readResult.ok) {
const error = readResult.error;
if (error.code === "cancelled") return err(cancelled());
if (error.code === "unsupported")
return err(failure("unsupported", error.message));
return err(failure("io", error.message));
}
const vcs = vcsResult.value;
if (isAborted(options.signal)) return err(cancelled(readResult.value));
if (isAborted(options.signal)) return err(cancelled());
const read = readResult.value;
const filePaths = new Set(
@@ -226,7 +175,7 @@ export const importReferenceSource = async (
const { entries, relationships, parseFailures, limitations } =
parseReferenceSourceEntries(read, filePaths, options.signal);
if (isAborted(options.signal)) return err(cancelled(read));
if (isAborted(options.signal)) return err(cancelled());
const uniqueRelationships = deduplicateRelationships(relationships);
const uniqueFailures = normalizeHistoricalSourceParseFailures(parseFailures);
@@ -272,45 +221,3 @@ export const importReferenceSource = async (
);
}
};
const combineReadFailures = (
primary: ReferenceSourceReaderError,
other: ReferenceSourceReaderError | undefined,
partial: ReferenceSourceRead | undefined,
): ReferenceSourceImportError => {
const code =
primary.code === "cancelled" || other?.code === "cancelled"
? "cancelled"
: primary.code;
const cleanup = mergeCleanup(primary.cleanup, other?.cleanup);
const message =
other === undefined
? primary.message
: `${primary.message}; additional reference metadata failure: ${other.message}`;
const cause =
other === undefined
? primary.cause
: new AggregateError(
[primary, other],
"Reference source inventory and metadata both failed",
{ cause: primary },
);
return {
...failure(code, message),
...(cleanup === undefined ? {} : { cleanup }),
...(partial === undefined ? {} : { partial }),
...(cause === undefined ? {} : { cause }),
};
};
const mergeCleanup = (
first: AnalysisCleanupObservation | undefined,
second: AnalysisCleanupObservation | undefined,
): AnalysisCleanupObservation | undefined => {
if (first === undefined) return second;
if (second === undefined) return first;
return {
reason: `${first.reason}; ${second.reason}`,
resources: [...new Set([...first.resources, ...second.resources])],
};
};
+27 -112
View File
@@ -2,21 +2,14 @@ import { lstat, realpath, stat } from "node:fs/promises";
import { join, resolve } from "node:path";
import ignore from "ignore";
import {
readRegularFileText,
RegularFileCleanupFailure,
retryRegularFileCleanup,
} from "./RegularFileRead.js";
import { readRegularFileText } from "./RegularFileRead.js";
import { err, ok, type Result } from "../domain/result.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import {
DEFAULT_REFERENCE_SOURCE_IGNORE_PATTERNS,
type ReferenceSourceImportError,
type ReferenceSourceImportOptions,
} from "./ReferenceSourceImportTypes.js";
import { rootFilesystemFailure } from "../reference/ReferenceSourceReaderErrors.js";
/** Validated inputs ready for filesystem traversal. */
export interface PreparedReferenceSourceImport {
@@ -34,57 +27,29 @@ const failure = (
message,
});
const isAborted = (signal?: AbortSignal): boolean => signal?.aborted === true;
const addMarkedPatterns = (
matcher: ReturnType<typeof ignore>,
patterns: readonly string[],
mark: "project-ignored" | "default-ignored" | "caller-excluded",
): void => {
for (const pattern of patterns)
for (const line of pattern.split(/\r?\n/u))
matcher.add({ pattern: line, mark });
};
const resolveRoot = async (
requestedRoot: string,
signal?: AbortSignal,
): Promise<Result<string, ReferenceSourceImportError>> => {
if (isAborted(signal))
return err(failure("cancelled", "Reference source import cancelled"));
try {
const metadata = await stat(requestedRoot);
if (isAborted(signal))
return err(failure("cancelled", "Reference source import cancelled"));
if (!metadata.isDirectory())
if (!(await stat(requestedRoot)).isDirectory())
return err(
failure(
"invalid-root",
`Reference source root is not a directory: ${requestedRoot}`,
),
failure("invalid-root", "Reference source root is not a directory"),
);
const canonicalRoot = await realpath(resolve(requestedRoot));
if (isAborted(signal))
return err(failure("cancelled", "Reference source import cancelled"));
return ok(canonicalRoot);
} catch (cause: unknown) {
if (isAborted(signal))
return err(failure("cancelled", "Reference source import cancelled"));
const rootFailure = rootFilesystemFailure(
cause,
"Reference source root could not be resolved",
void cause;
return err(
failure("invalid-root", "Reference source root could not be resolved"),
);
if (rootFailure === undefined) throw cause;
return err({ ...failure(rootFailure.code, rootFailure.message), cause });
}
};
const buildIgnored = async (
root: string,
excludePaths: readonly string[],
resources: ArtifactResourceScope,
signal?: AbortSignal,
): Promise<Result<ReturnType<typeof ignore>, ReferenceSourceImportError>> => {
): Promise<ReturnType<typeof ignore>> => {
const ignored = ignore();
const policyPath = join(root, ".gitignore");
let present = true;
@@ -103,89 +68,39 @@ const buildIgnored = async (
present = false;
}
signal?.throwIfAborted();
if (present) {
let text: string;
try {
text = await readRegularFileText(policyPath, { signal });
} catch (cause: unknown) {
if (!(cause instanceof RegularFileCleanupFailure)) throw cause;
const retry = await retryRegularFileCleanup(cause, resources);
if (retry.cleanup !== undefined) {
const primary =
cause.outcome.kind === "failed"
? cause.outcome.cause
: cause.cleanupCause;
return err({
...failure(
signal?.aborted === true ? "cancelled" : "io",
`Reference source ignore policy could not be read at ${policyPath}: ${errorMessage(primary)}`,
),
cleanup: retry.cleanup,
cause: primary,
});
}
if (retry.outcome.kind === "failed") throw retry.outcome.cause;
text = retry.outcome.value;
}
addMarkedPatterns(ignored, [text], "project-ignored");
}
addMarkedPatterns(
ignored,
DEFAULT_REFERENCE_SOURCE_IGNORE_PATTERNS,
"default-ignored",
);
if (present) ignored.add(await readRegularFileText(policyPath, { signal }));
ignored.add([...DEFAULT_REFERENCE_SOURCE_IGNORE_PATTERNS]);
for (const path of excludePaths) {
addMarkedPatterns(ignored, [path, `${path}/`], "caller-excluded");
ignored.add(path);
ignored.add(`${path}/`);
}
return ok(ignored);
return ignored;
};
/** Resolve the caller-selected directory and build path filters. */
export const prepareReferenceSourceImport = async (
options: ReferenceSourceImportOptions,
resources: ArtifactResourceScope,
): Promise<
Result<PreparedReferenceSourceImport, ReferenceSourceImportError>
> => {
const root = await resolveRoot(options.root);
if (!root.ok) return root;
try {
return await resources.run(async () => {
const root = await resolveRoot(options.root, options.signal);
if (!root.ok) return root;
try {
const ignored = await buildIgnored(
root.value,
options.excludePaths ?? [],
resources,
options.signal,
);
if (!ignored.ok) return ignored;
return ok({
root: root.value,
ignored: ignored.value,
secrets: ignore().add([...options.policy.secretPatterns]),
});
} catch (cause: unknown) {
return err({
...failure(
options.signal?.aborted === true ? "cancelled" : "io",
`Reference source ignore policy could not be read at ${join(root.value, ".gitignore")}: ${errorMessage(cause)}`,
),
cause,
});
}
return ok({
root: root.value,
ignored: await buildIgnored(
root.value,
options.excludePaths ?? [],
options.signal,
),
secrets: ignore().add([...options.policy.secretPatterns]),
});
} catch (cause: unknown) {
if (!(cause instanceof ArtifactReaderFailure)) throw cause;
return err({
...failure(
cause.reason === "cancelled" ? "cancelled" : "io",
cause.message,
return err(
failure(
options.signal?.aborted === true ? "cancelled" : "io",
`Reference source ignore policy could not be read at ${join(root.value, ".gitignore")}: ${cause instanceof Error ? cause.message : String(cause)}`,
),
...(cause.cleanup === undefined ? {} : { cleanup: cause.cleanup }),
cause,
});
);
}
};
const errorMessage = (cause: unknown): string =>
cause instanceof Error ? cause.message : String(cause);
@@ -1,80 +0,0 @@
import { describe, expect, it } from "vitest";
import {
projectReferenceSourceImportError,
type ReferenceSourceImportError,
} from "./ReferenceSourceImportTypes.js";
import type { ReferenceSourceRead } from "../reference/ReferenceSourceReaderTypes.js";
describe("reference-source import error projection", () => {
it("preserves primary evidence with category-specific recovery guidance", () => {
const expectedCategories = {
cancelled: "cancelled",
"invalid-root": "invalid_input",
unsupported: "unsupported_host",
io: "execution_failure",
parse: "execution_failure",
} as const;
for (const [code, category] of Object.entries(expectedCategories)) {
const projected = projectReferenceSourceImportError({
tag: "reference-source-import",
code: code as ReferenceSourceImportError["code"],
message: "EIO while reading /selected/source/src/main.ts",
});
expect(projected.category).toBe(category);
expect(projected.message).toContain(
"EIO while reading /selected/source/src/main.ts",
);
expect(projected.message).toMatch(
/try again|when ready|Check that|REA on Linux/u,
);
}
});
it("preserves cancellation, partial facts, and cleanup diagnostics", () => {
const bytes = Buffer.from("export const observed = true;\n");
const partial: ReferenceSourceRead = {
root: "/selected/source",
entries: [
{
status: "read",
kind: "file",
path: "src/main.ts",
bytes,
size: bytes.length,
},
],
bytesRead: bytes.length,
limitations: [],
};
const projected = projectReferenceSourceImportError({
tag: "reference-source-import",
code: "cancelled",
message: "Traversal cancelled after reading src/main.ts",
cleanup: {
reason: "directory close rejected",
resources: ["/selected/source"],
},
partial,
});
expect(projected).toMatchObject({
category: "cancelled",
message: expect.stringContaining(
"Traversal cancelled after reading src/main.ts",
),
cleanup: {
reason: "directory close rejected",
resources: ["/selected/source"],
},
partial: {
root: "/selected/source",
entries: [{ path: "src/main.ts", bytes }],
},
});
expect(projected.message).toContain("Cleanup failed during import");
expect(projected.message).toContain("directory close rejected");
expect(projected.message).toContain("/selected/source");
expect(projected.message).not.toContain("remains unconfirmed");
});
});
+28 -51
View File
@@ -1,67 +1,44 @@
import type { ReferenceSourcePolicy } from "../domain/referenceSourcePolicy.js";
import type { AnalysisCleanupObservation } from "../domain/analysisErrorBase.js";
import type { ReferenceSourceRead } from "../reference/ReferenceSourceReaderTypes.js";
/** Typed expected failure returned by historical-source imports. */
export interface ReferenceSourceImportError {
readonly tag: "reference-source-import";
readonly code: "cancelled" | "invalid-root" | "unsupported" | "io" | "parse";
readonly message: string;
readonly cleanup?: AnalysisCleanupObservation;
readonly partial?: ReferenceSourceRead;
readonly cause?: unknown;
}
const IMPORT_FAILURE_GUIDANCE = {
cancelled: {
category: "cancelled",
message:
"Reference source import was cancelled. Start it again when ready.",
},
"invalid-root": {
category: "invalid_input",
message:
"Reference source directory could not be opened. Check that the path exists, is readable, and points to a directory.",
},
unsupported: {
category: "unsupported_host",
message:
"Safe no-follow file opens are unavailable on this host. Import the source tree with REA on Linux (including WSL) or macOS.",
},
io: {
category: "execution_failure",
message:
"Reference source files could not be read. Check directory permissions and try again.",
},
parse: {
category: "execution_failure",
message:
"Reference source could not be indexed. Check that the source tree is readable, then try again.",
},
} satisfies Record<
ReferenceSourceImportError["code"],
{ readonly category: string; readonly message: string }
>;
/** Safe CLI projection for a historical-source import failure. */
export const projectReferenceSourceImportError = (
error: ReferenceSourceImportError,
): Readonly<{
category: string;
message: string;
cleanup?: AnalysisCleanupObservation;
partial?: ReferenceSourceRead;
}> => {
const primary = IMPORT_FAILURE_GUIDANCE[error.code];
const cleanupMessage =
error.cleanup === undefined
? ""
: ` Cleanup failed during import for ${error.cleanup.resources.join(", ")}: ${error.cleanup.reason}.`;
): Readonly<{ category: string; message: string }> => {
if (error.code === "cancelled")
return {
category: "cancelled",
message:
"Reference source import was cancelled. Start it again when ready.",
};
if (error.code === "invalid-root")
return {
category: "invalid_input",
message:
"Reference source directory could not be opened. Check that the path exists, is readable, and points to a directory.",
};
if (error.code === "unsupported")
return {
category: "unsupported_host",
message:
"Safe no-follow file opens are unavailable on this host. Import the source tree with REA on Linux (including WSL) or macOS.",
};
if (error.code === "io")
return {
category: "execution_failure",
message:
"Reference source files could not be read. Check directory permissions and try again.",
};
return {
category: primary.category,
message: `${error.message} ${primary.message}${cleanupMessage}`,
...(error.cleanup === undefined ? {} : { cleanup: error.cleanup }),
...(error.partial === undefined ? {} : { partial: error.partial }),
category: "execution_failure",
message:
"Reference source could not be indexed. Check that the source tree is readable, then try again.",
};
};
+46 -149
View File
@@ -1,15 +1,7 @@
import fs from "node:fs";
import { lstat } from "node:fs/promises";
import { join, resolve } from "node:path";
import { err, ok, type Result } from "../domain/result.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import {
readRegularFile,
RegularFileCleanupFailure,
retryRegularFileCleanup,
} from "./RegularFileRead.js";
import type { ReferenceSourceReaderError } from "../reference/ReferenceSourceReaderTypes.js";
import { readRegularFile, readRegularFileText } from "./RegularFileRead.js";
export type ReferenceSourceVcsInfo =
| {
@@ -27,147 +19,61 @@ export type ReferenceSourceVcsInfo =
*/
export const readReferenceSourceVcs = async (
root: string,
resources: ArtifactResourceScope,
signal?: AbortSignal,
): Promise<Result<ReferenceSourceVcsInfo, ReferenceSourceReaderError>> => {
): Promise<ReferenceSourceVcsInfo> => {
if (isAborted(signal)) return { kind: "unknown", head: null, dirty: null };
try {
return await resources.run(async () => {
if (isAborted(signal)) return ok(unknownVcs());
try {
await lstat(join(root, ".git"));
} catch (cause: unknown) {
return ok(
errorCode(cause) === "ENOENT"
? { kind: "none", head: null, dirty: null }
: unknownVcs(),
);
}
try {
const head = await resolveSourceHead(root, resources, signal);
if (isAborted(signal)) return ok(unknownVcs());
return ok({ kind: "git", head, dirty: null });
} catch (cause: unknown) {
if (cause instanceof ArtifactReaderFailure) throw cause;
return ok(unknownVcs());
}
});
await lstat(join(root, ".git"));
} catch (cause: unknown) {
if (!(cause instanceof ArtifactReaderFailure)) throw cause;
return err({
tag: "reference-source-reader",
code: cause.reason === "cancelled" ? "cancelled" : "io",
message: cause.message,
...(cause.cleanup === undefined ? {} : { cleanup: cause.cleanup }),
cause,
});
return errorCode(cause) === "ENOENT"
? { kind: "none", head: null, dirty: null }
: { kind: "unknown", head: null, dirty: null };
}
try {
const head = await resolveSourceHead(root, signal);
if (isAborted(signal)) return { kind: "unknown", head: null, dirty: null };
return { kind: "git", head, dirty: null };
} catch (cause: unknown) {
// Unresolvable refs mean VCS state is unknown, not absent.
void cause;
return { kind: "unknown", head: null, dirty: null };
}
};
const unknownVcs = (): ReferenceSourceVcsInfo => ({
kind: "unknown",
head: null,
dirty: null,
});
const resolveSourceHead = async (
root: string,
resources: ArtifactResourceScope,
signal?: AbortSignal,
): Promise<string> => {
// isomorphic-git is loaded on first use so CLI and MCP startup skip it.
const { resolveRef } = await import("isomorphic-git");
let failedRead: { readonly cause: unknown } | undefined;
const cleanupFailures: ArtifactReaderFailure[] = [];
const readMetadataBytes = async (path: string): Promise<Buffer> => {
try {
return await readRegularFile(path, { signal });
} catch (cause: unknown) {
if (!(cause instanceof RegularFileCleanupFailure)) throw cause;
const retry = await retryRegularFileCleanup(cause, resources);
if (
retry.outcome.kind === "failed" &&
errorCode(retry.outcome.cause) !== "ENOENT"
)
failedRead ??= { cause: retry.outcome.cause };
if (
retry.cleanup === undefined &&
retry.outcome.kind === "failed" &&
!isAborted(signal)
)
throw retry.outcome.cause;
const primary =
retry.outcome.kind === "failed"
? retry.outcome.cause
: cause.cleanupCause;
throw new ArtifactReaderFailure(
isAborted(signal) ? "cancelled" : "io",
`Git metadata could not be read safely: ${errorMessage(primary)}`,
{
cause: primary,
...(retry.cleanup === undefined ? {} : { cleanup: retry.cleanup }),
},
);
}
};
const readMetadataText = async (path: string): Promise<string> =>
(await readMetadataBytes(path)).toString("utf8");
const throwCleanupFailures = (primary: unknown): never => {
const observations = cleanupFailures.flatMap((failure) =>
failure.cleanup === undefined ? [] : [failure.cleanup],
);
throw new ArtifactReaderFailure(
isAborted(signal) ? "cancelled" : "io",
`Git metadata could not be read safely: ${errorMessage(primary)}`,
{
cause: new AggregateError(
[primary, ...cleanupFailures],
"Git metadata reads and cleanup failed",
{ cause: primary },
),
...(observations.length === 0
? {}
: {
cleanup: {
reason: observations.map(({ reason }) => reason).join("; "),
resources: [
...new Set(
observations.flatMap(({ resources }) => resources),
),
],
},
}),
},
);
};
const referenceFs = {
...fs,
promises: {
...fs.promises,
// Let isomorphic-git continue from a failed loose ref to packed-refs,
// then report the original read failure after resolution. This preserves
// both observations when packed metadata also fails cleanup.
readFile: async (
path: string | undefined,
options:
| BufferEncoding
| { readonly encoding?: BufferEncoding | null }
| null = null,
) => {
// The library probes readFile() without a path to detect promise APIs.
// Reject that invocation without attributing it to a source read.
// isomorphic-git treats every read failure as absence. Preserve real
// failures so a readable packed ref cannot hide an unreadable loose ref.
readFile: async (path?: string, options?: unknown) => {
// isomorphic-git probes promise support with readFile() before reading
// metadata. Its rejected probe must not count as a failed file read.
if (path === undefined)
throw new TypeError("Git filesystem read requires a path");
throw new TypeError("Git metadata path is required");
try {
const bytes = await readMetadataBytes(path);
const bytes = await readRegularFile(path, { signal });
const encoding =
typeof options === "string" ? options : options?.encoding;
return encoding === undefined || encoding === null
? bytes
: bytes.toString(encoding);
typeof options === "string"
? options
: typeof options === "object" &&
options !== null &&
"encoding" in options
? options.encoding
: undefined;
if (encoding === undefined || encoding === null) return bytes;
if (typeof encoding !== "string" || !Buffer.isEncoding(encoding))
throw new TypeError("Unsupported Git metadata text encoding");
return bytes.toString(encoding);
} catch (cause: unknown) {
if (cause instanceof ArtifactReaderFailure) {
cleanupFailures.push(cause);
} else if (errorCode(cause) !== "ENOENT") failedRead ??= { cause };
if (errorCode(cause) !== "ENOENT") failedRead ??= { cause };
throw cause;
}
},
@@ -177,24 +83,17 @@ const resolveSourceHead = async (
readonly gitdir?: string;
readonly ref: string;
}) => {
let head: string;
try {
head = await resolveRef({ fs: referenceFs, dir: root, ...options });
} catch (cause: unknown) {
if (cleanupFailures.length > 0)
throwCleanupFailures(failedRead?.cause ?? cause);
if (failedRead !== undefined) throw failedRead.cause;
throw cause;
}
if (cleanupFailures.length > 0)
throwCleanupFailures(failedRead?.cause ?? cleanupFailures[0]?.cause);
const head = await resolveRef({ fs: referenceFs, dir: root, ...options });
signal?.throwIfAborted();
if (failedRead !== undefined) throw failedRead.cause;
return head;
};
const dotgit = join(root, ".git");
if (!(await lstat(dotgit)).isFile()) return readRef({ ref: "HEAD" });
const pointer = (await readMetadataText(dotgit)).replace(/\r?\n$/u, "");
const pointer = (await readRegularFileText(dotgit, { signal })).replace(
/\r?\n$/u,
"",
);
if (!pointer.startsWith("gitdir: ") || pointer.length === 8)
throw new Error("Invalid Git directory pointer");
const gitdir = resolve(root, pointer.slice(8));
@@ -202,16 +101,17 @@ const resolveSourceHead = async (
try {
commonDirectory = resolve(
gitdir,
(await readMetadataText(join(gitdir, "commondir"))).replace(
/\r?\n$/u,
"",
),
(
await readRegularFileText(join(gitdir, "commondir"), { signal })
).replace(/\r?\n$/u, ""),
);
} catch (cause: unknown) {
if (errorCode(cause) !== "ENOENT") throw cause;
return readRef({ gitdir, ref: "HEAD" });
}
const head = (await readMetadataText(join(gitdir, "HEAD"))).trim();
const head = (
await readRegularFileText(join(gitdir, "HEAD"), { signal })
).trim();
if (!head.startsWith("ref: ")) return readRef({ gitdir, ref: "HEAD" });
const ref = head.slice(5);
const privateRef = ["refs/bisect/", "refs/rewritten/", "refs/worktree/"].some(
@@ -228,7 +128,4 @@ const errorCode = (cause: unknown): string | undefined =>
? String(cause.code)
: undefined;
const errorMessage = (cause: unknown): string =>
cause instanceof Error ? cause.message : String(cause);
const isAborted = (signal?: AbortSignal): boolean => signal?.aborted === true;
+8 -94
View File
@@ -2,15 +2,11 @@ import type { Stats } from "node:fs";
import { lstat, stat, type FileHandle } from "node:fs/promises";
import {
RegularFileAdmissionFailure,
openRegularFile,
sameRegularFileState,
RegularFileChangedError,
} from "../filesystem/RegularFile.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import type { AnalysisCleanupObservation } from "../domain/analysisErrorBase.js";
/** Filesystem admission policy for one selected regular input. */
export interface RegularFileReadOptions {
@@ -18,51 +14,6 @@ export interface RegularFileReadOptions {
readonly symlinks?: "follow" | "reject";
}
export type RegularFileReadOutcome<Value> =
| { readonly kind: "completed"; readonly value: Value }
| { readonly kind: "failed"; readonly cause: unknown };
/** A close failed after reading; this error transfers the exact handle owner. */
export class RegularFileCleanupFailure<Value = unknown> extends Error {
constructor(
readonly path: string,
readonly owner: OwnedFileHandle,
readonly outcome: RegularFileReadOutcome<Value>,
readonly cleanupCause: unknown,
) {
super(`Regular file cleanup failed: ${path}`, {
cause: outcome.kind === "failed" ? outcome.cause : cleanupCause,
});
this.name = "RegularFileCleanupFailure";
}
}
/** Retry a failed close through its retained owner and report any remaining cleanup. */
export const retryRegularFileCleanup = async <Value>(
failure: RegularFileCleanupFailure<Value>,
resources: ArtifactResourceScope,
): Promise<{
readonly outcome: RegularFileReadOutcome<Value>;
readonly cleanup?: AnalysisCleanupObservation;
}> => {
const released = await resources.release({
kind: "file-handle",
handle: failure.owner,
resource: failure.path,
});
if (released.kind === "released") return { outcome: failure.outcome };
return {
outcome: failure.outcome,
cleanup: {
reason: `${failureMessage(failure.cleanupCause)}; retry: ${failureMessage(released.cause)}`,
resources: [failure.path],
},
};
};
const failureMessage = (cause: unknown): string =>
cause instanceof Error ? cause.message : String(cause);
/** Admit one regular-file handle, retain it through the consumer, and always close it. */
export const withRegularFile = async <Value>(
path: string,
@@ -70,23 +21,10 @@ export const withRegularFile = async <Value>(
options: RegularFileReadOptions = {},
): Promise<Value> => {
const { signal } = options;
let handle: FileHandle;
try {
handle = await openRegularFile(path, {
symlinks: options.symlinks ?? "follow",
signal,
});
} catch (cause: unknown) {
if (!(cause instanceof RegularFileAdmissionFailure)) throw cause;
throw new RegularFileCleanupFailure(
path,
cause.owner,
{ kind: "failed", cause: cause.cause },
cause.cleanupCause,
);
}
const owner = new OwnedFileHandle(handle);
let outcome: RegularFileReadOutcome<Value>;
const handle = await openRegularFile(path, {
symlinks: options.symlinks ?? "follow",
signal,
});
try {
const stats = await handle.stat();
signal?.throwIfAborted();
@@ -101,17 +39,10 @@ export const withRegularFile = async <Value>(
!sameRegularFileState(stats, currentPath)
)
throw new RegularFileChangedError(path);
outcome = { kind: "completed", value };
} catch (cause: unknown) {
outcome = { kind: "failed", cause };
return value;
} finally {
await handle.close();
}
try {
await owner.close();
} catch (cleanupCause: unknown) {
throw new RegularFileCleanupFailure(path, owner, outcome, cleanupCause);
}
if (outcome.kind === "failed") throw outcome.cause;
return outcome.value;
};
/** Admit a regular file without waiting for a pipe, then read its verified handle. */
@@ -138,21 +69,4 @@ export const readRegularFile = (
export const readRegularFileText = async (
path: string,
options: RegularFileReadOptions = {},
): Promise<string> => {
try {
return (await readRegularFile(path, options)).toString("utf8");
} catch (cause: unknown) {
if (
cause instanceof RegularFileCleanupFailure &&
cause.outcome.kind === "completed" &&
Buffer.isBuffer(cause.outcome.value)
)
throw new RegularFileCleanupFailure(
cause.path,
cause.owner,
{ kind: "completed", value: cause.outcome.value.toString("utf8") },
cause.cleanupCause,
);
throw cause;
}
};
): Promise<string> => (await readRegularFile(path, options)).toString("utf8");
-73
View File
@@ -1,8 +1,5 @@
import { describe, expect, it } from "vitest";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { ConfigurationError } from "../domain/configurationErrors.js";
import { SUPPORTED_NODE_VERSION_PROSE } from "../domain/runtimeVersion.js";
import { FakeSetupHost, options } from "./Setup.fixture.js";
import { runSetup } from "./Setup.js";
@@ -110,76 +107,6 @@ describe("setup workflow", () => {
});
});
describe("setup failure cleanup projection", () => {
it("projects a configuration failure together with failed host cleanup", async () => {
const configPath = "/fixture/home/vscode/settings.json";
const primary = new ConfigurationError("Client config could not be read", {
settings: [
{
setting: configPath,
constraint: "The selected config could not be read.",
},
],
cleanup: {
reason: "The admitted config handle remains open.",
resources: [configPath],
},
});
class SetupHostWithCleanupFailure extends FakeSetupHost {
close = async (): Promise<string> =>
"Setup could not release its client configuration resources.";
}
const host = new SetupHostWithCleanupFailure();
host.clients = [{ name: "codex", configPath }];
host.inspectClientConfiguration = async () => {
throw primary;
};
const failure = await runSetup(
{ ...options(true), clientIds: ["codex"] },
host,
).then(
() => undefined,
(cause: unknown) => cause,
);
expect(failure).toBeInstanceOf(AnalysisError);
if (!(failure instanceof AnalysisError))
throw new Error("Expected setup to preserve a typed analysis failure");
const projected = projectAnalysisError(failure);
expect(projected).toMatchObject({
code: "cleanup_incomplete",
details: {
cleanup: "incomplete",
resources: [configPath],
diagnostics: {
primary_error: {
code: "cleanup_incomplete",
details: { resources: [configPath] },
},
cleanup_error: {
code: "cleanup_incomplete",
details: { resources: [configPath] },
},
},
},
});
expect(projected.details).toMatchObject({
diagnostics: {
primary_error: { message: expect.stringContaining("selected config") },
cleanup_error: {
details: {
diagnostics: {
reason:
"Setup could not release its client configuration resources.",
},
},
},
},
});
});
});
describe("setup scoped readiness", () => {
it("limits Hopper host checks to workflows that request Hopper", async () => {
const platformHost = new FakeSetupHost("win32");
-14
View File
@@ -23,9 +23,6 @@ import {
hostRemediation,
systemSetupHost,
} from "./SetupHost.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
/** Discover, approve, and apply setup actions idempotently. */
export const runSetup = async (
@@ -51,17 +48,6 @@ export const runSetup = async (
}
if (threw) {
if (cleanupFailure !== undefined && primaryFailure instanceof AnalysisError)
throw analysisErrorWithCleanupFailure(
primaryFailure,
new ProviderCleanupError(
"setup",
primaryFailure.cleanupResources,
{ reason: cleanupFailure },
{ operation: "setup" },
),
"setup",
);
if (cleanupFailure !== undefined)
throw new AggregateError(
[primaryFailure, new Error(cleanupFailure)],
+43 -115
View File
@@ -11,22 +11,18 @@ import {
serializeClientConfiguration,
withClientServers,
type ClientConfigurationDocument,
type ClientRegistrationDialect,
} from "./ClientConfigurationDocument.js";
import { constants as fsConstants } from "node:fs";
import { copyFile, mkdir, rm, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import writeFileAtomic from "write-file-atomic";
import { clientRegistrationEnvironment } from "./ClientRegistrationEnvironment.js";
import { PRODUCT_IDENTITY } from "../identity.js";
import { npxRegistrationCommand } from "./ClientRegistrationIdentity.js";
import { MCP_STARTUP_POLICY } from "../mcpStartupPolicy.js";
import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js";
import {
readRegularFileText,
RegularFileCleanupFailure,
} from "./RegularFileRead.js";
import type { ClientConfigurationFileError } from "./ClientConfigurationFiles.js";
import { readRegularFileText } from "./RegularFileRead.js";
import type {
ClientConfigurationInspection,
ClientConfigurationResult,
@@ -42,37 +38,25 @@ export const configureClientConfiguration = (
): Promise<ClientConfigurationResult> => {
if (client.configPathError !== undefined)
return Promise.resolve({ status: "failed", reason: "path" });
return configureClientDocument(client, environment, command);
if (client.format === undefined || client.format === "unsupported")
return Promise.resolve({ status: "failed", reason: "readback" });
return configureClientDocument(client, environment, command, client.format);
};
const configureClientDocument = async (
client: SetupClient,
environment: SetupProviderEnvironment,
command: readonly string[],
format: NonNullable<SetupClient["format"]>,
): Promise<ClientConfigurationResult> => {
const format = client.format;
if (format === undefined || format === "unsupported")
return { status: "failed", reason: "readback" };
const files = await readClientConfigurationFiles(client);
if (!files.ok) {
throwCleanupFailure(files.error);
return { status: "failed", reason: "readback" };
}
if (!files.ok) return { status: "failed", reason: "readback" };
const policy = await readClientPolicyBlock(
client,
undefined,
clientConfigurationDesired(
client,
environment,
command,
files.value.at(-1),
),
clientConfigurationDesired(client, environment, command, client.format),
);
if (!policy.ok) {
throwCleanupFailure(policy.error);
return { status: "failed", reason: "readback" };
}
if (policy.value !== undefined)
if (!policy.ok || policy.value !== undefined)
return { status: "failed", reason: "readback" };
const transactionPath = await resolveClientConfigTransactionPath(
client.configPath,
@@ -83,7 +67,6 @@ const configureClientDocument = async (
try {
original = await readRegularFileText(transactionPath);
} catch (cause: unknown) {
if (cause instanceof RegularFileCleanupFailure) throw cause;
if (!isMissing(cause)) return { status: "failed", reason: "readback" };
}
let parsed: ClientConfigurationDocument;
@@ -95,16 +78,11 @@ const configureClientDocument = async (
const policy = await readClientPolicyBlock(
client,
parsed,
clientConfigurationDesired(client, environment, command, parsed),
clientConfigurationDesired(client, environment, command, parsed.dialect),
);
if (!policy.ok) {
throwCleanupFailure(policy.error);
return { status: "failed", reason: "readback" };
}
if (policy.value !== undefined)
if (!policy.ok || policy.value !== undefined)
return { status: "failed", reason: "readback" };
} catch (cause: unknown) {
if (cause instanceof RegularFileCleanupFailure) throw cause;
// Malformed existing configuration fails the readback gate.
void cause;
return { status: "failed", reason: "readback" };
@@ -113,36 +91,9 @@ const configureClientDocument = async (
client,
environment,
command,
parsed,
parsed.dialect,
);
if (registrationCurrent(parsed, desired)) return { status: "unchanged" };
return persistClientConfiguration({
client,
transactionPath,
format,
original,
parsed,
desired,
});
};
interface ClientConfigurationUpdate {
readonly client: SetupClient;
readonly transactionPath: string;
readonly format: NonNullable<SetupClient["format"]>;
readonly original: string | undefined;
readonly parsed: ClientConfigurationDocument;
readonly desired: unknown;
}
const persistClientConfiguration = async ({
client,
transactionPath,
format,
original,
parsed,
desired,
}: ClientConfigurationUpdate): Promise<ClientConfigurationResult> => {
const backupPath =
original === undefined ? undefined : `${client.configPath}.rea.backup`;
if (
@@ -207,7 +158,6 @@ const persistClientConfiguration = async ({
return { status: "failed", reason: "readback" };
}
} catch (cause: unknown) {
if (cause instanceof RegularFileCleanupFailure) throw cause;
// Readback failure restores the transaction before reporting.
void cause;
await restoreConfig(transactionPath, original);
@@ -228,22 +178,21 @@ export const clientConfigurationAligned = async (
if (client.configPathError !== undefined) return false;
try {
const files = await readClientConfigurationFiles(client);
if (!files.ok) {
throwCleanupFailure(files.error);
return false;
}
if (!files.ok) return false;
const original = await readRegularFileText(client.configPath);
const parsed = parseClientConfiguration(original, client.format);
const policy = await readClientPolicyBlock(
client,
parsed,
clientConfigurationDesired(client, providerEnvironment, command, parsed),
clientConfigurationDesired(
client,
providerEnvironment,
command,
parsed.dialect,
),
);
if (!policy.ok) {
throwCleanupFailure(policy.error);
return false;
}
return (
policy.ok &&
policy.value === undefined &&
registrationCurrent(
parsed,
@@ -251,12 +200,11 @@ export const clientConfigurationAligned = async (
client,
providerEnvironment,
command,
parsed,
parsed.dialect,
),
)
);
} catch (cause: unknown) {
if (cause instanceof RegularFileCleanupFailure) throw cause;
// Unreadable configuration is treated as not aligned so setup repairs it.
void cause;
return false;
@@ -273,13 +221,7 @@ export const inspectClientConfiguration = async (
return { status: "invalid", remediation: client.configPathError };
if (client.format === "unsupported") return { status: "already_current" };
const files = await readClientConfigurationFiles(client);
if (!files.ok) {
throwCleanupFailure(files.error);
return {
status: "invalid",
remediation: files.error.detail,
};
}
if (!files.ok) return { status: "invalid", remediation: files.error.detail };
const policy = await readClientPolicyBlock(
client,
undefined,
@@ -287,16 +229,11 @@ export const inspectClientConfiguration = async (
client,
providerEnvironment,
command,
files.value.at(-1),
client.format,
),
);
if (!policy.ok) {
throwCleanupFailure(policy.error);
return {
status: "invalid",
remediation: policy.error.detail,
};
}
if (!policy.ok)
return { status: "invalid", remediation: policy.error.detail };
if (policy.value !== undefined)
return { status: "invalid", remediation: policy.value };
const transactionPath = await resolveClientConfigTransactionPath(
@@ -312,11 +249,11 @@ export const inspectClientConfiguration = async (
try {
original = await readRegularFileText(transactionPath);
} catch (cause: unknown) {
if (cause instanceof RegularFileCleanupFailure) throw cause;
if (isMissing(cause)) return { status: "create" };
return {
status: "invalid",
remediation: `The configuration file could not be read. Check its permissions before rerunning setup. ${cause instanceof Error ? cause.message : String(cause)}`,
remediation:
"The configuration file could not be read. Check its permissions before rerunning setup.",
};
}
try {
@@ -324,27 +261,26 @@ export const inspectClientConfiguration = async (
const policy = await readClientPolicyBlock(
client,
parsed,
clientConfigurationDesired(client, providerEnvironment, command, parsed),
clientConfigurationDesired(
client,
providerEnvironment,
command,
parsed.dialect,
),
);
if (!policy.ok) {
throwCleanupFailure(policy.error);
return {
status: "invalid",
remediation: policy.error.detail,
};
}
if (!policy.ok)
return { status: "invalid", remediation: policy.error.detail };
if (policy.value !== undefined)
return { status: "invalid", remediation: policy.value };
const desired = clientConfigurationDesired(
client,
providerEnvironment,
command,
parsed,
parsed.dialect,
);
if (registrationCurrent(parsed, desired))
return { status: "already_current" };
} catch (cause: unknown) {
if (cause instanceof RegularFileCleanupFailure) throw cause;
// Malformed configuration is reported with the invalid remediation.
void cause;
return {
@@ -361,11 +297,6 @@ export const inspectClientConfiguration = async (
const isMissing = (cause: unknown): boolean =>
cause instanceof Error && "code" in cause && cause.code === "ENOENT";
const throwCleanupFailure = (error: ClientConfigurationFileError): void => {
if (error.cleanupFailure !== undefined) throw error.cleanupFailure;
};
const preserveConfigBackup = async (
source: string,
destination: string,
@@ -407,20 +338,17 @@ const clientConfigurationDesired = (
client: SetupClient,
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
parsed?: ClientConfigurationDocument,
format: ClientRegistrationDialect | undefined,
) => {
const format = parsed?.dialect ?? client.format ?? "json";
// Preserve explicitly configured server settings, never the ambient process
// environment. Newly discovered provider paths win only for their own keys.
const environment = clientRegistrationEnvironment(
parsed,
providerEnvironment,
const environment = Object.fromEntries(
Object.entries(providerEnvironment).sort(([left], [right]) =>
left.localeCompare(right),
),
);
if (!environment.ok) throw environment.error;
const registration = clientRegistrationEntry(
format,
format ?? "json",
command.length === 0 ? [PRODUCT_IDENTITY.cliBinary, "mcp"] : command,
environment.value,
environment,
);
return {
...registration,
+12 -110
View File
@@ -1,9 +1,6 @@
import { access } from "node:fs/promises";
import { resolve } from "node:path";
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import { ConfigurationError } from "../domain/configurationErrors.js";
import { PRODUCT_IDENTITY } from "../identity.js";
import { npxRegistrationCommand } from "./ClientRegistrationIdentity.js";
import {
@@ -33,10 +30,6 @@ import {
inspectClientConfiguration,
} from "./SetupClientConfiguration.js";
import { setupInstallFailure } from "./SetupInstallFailure.js";
import {
RegularFileCleanupFailure,
retryRegularFileCleanup,
} from "./RegularFileRead.js";
import { providerRegistrationEnvironment } from "./SetupRegistrationEnvironment.js";
import type {
SetupHost,
@@ -105,7 +98,6 @@ export const systemSetupHost = (
platform === "darwin"
? systemMacHopperInstallHost(homeDirectory, environment)
: undefined;
const resources = new ArtifactResourceScope();
return {
platform,
homeDirectory,
@@ -118,7 +110,7 @@ export const systemSetupHost = (
nodeVersion: process.versions.node,
macosVersion: () => doctorHost.macosVersion(),
linuxDistribution: readLinuxDistribution,
close: () => closeSetupResources(resources, macHopperHost),
close: () => macHopperHost?.close() ?? Promise.resolve(undefined),
initialSetupState: async (
scope?: DoctorScope,
): Promise<SetupInitialState> => {
@@ -170,7 +162,17 @@ export const systemSetupHost = (
detectedClients: () => detectClients(homeDirectory, platform, environment),
supportedClients: () =>
Promise.resolve(supportedClients(homeDirectory, platform, environment)),
...clientConfigurationOperations(resources),
configureClient: (client, providerEnvironment, command) =>
client.format === "unsupported"
? Promise.resolve({ status: "skipped" })
: configureClientConfiguration(client, providerEnvironment, command),
clientNeedsConfigure: (client, providerEnvironment, command) =>
client.format === "unsupported"
? Promise.resolve(false)
: clientConfigurationAligned(client, providerEnvironment, command).then(
(aligned) => !aligned,
),
inspectClientConfiguration: inspectClientConfiguration,
skillNeedsInstall: (clientIds) =>
canonicalSkillNeedsInstall(
homeDirectory,
@@ -184,106 +186,6 @@ export const systemSetupHost = (
};
};
const clientConfigurationOperations = (resources: ArtifactResourceScope) => ({
configureClient: (
client: SetupClient,
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
) =>
runClientConfigurationOperation(resources, async () =>
client.format === "unsupported"
? { status: "skipped" as const }
: configureClientConfiguration(client, providerEnvironment, command),
),
clientNeedsConfigure: (
client: SetupClient,
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
) =>
runClientConfigurationOperation(resources, async () =>
client.format === "unsupported"
? false
: !(await clientConfigurationAligned(
client,
providerEnvironment,
command,
)),
),
inspectClientConfiguration: (
client: SetupClient,
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
) =>
runClientConfigurationOperation(resources, () =>
inspectClientConfiguration(client, providerEnvironment, command),
),
});
const closeSetupResources = async (
resources: ArtifactResourceScope,
macHopperHost: ReturnType<typeof systemMacHopperInstallHost> | undefined,
): Promise<string | undefined> => {
const [resourceCleanup, hopperCleanup] = await Promise.allSettled([
resources.close(),
Promise.resolve().then(() => macHopperHost?.close()),
]);
const failures: string[] = [];
if (hopperCleanup.status === "rejected")
failures.push(
`Hopper host cleanup failed: ${errorMessage(hopperCleanup.reason)}`,
);
else if (hopperCleanup.value !== undefined)
failures.push(hopperCleanup.value);
if (resourceCleanup.status === "rejected")
failures.push(errorMessage(resourceCleanup.reason));
return failures.length === 0 ? undefined : failures.join("; ");
};
const runClientConfigurationOperation = async <Value>(
resources: ArtifactResourceScope,
operation: () => Promise<Value>,
): Promise<Value> => {
try {
return await resources.run(async () => {
try {
return await operation();
} catch (cause: unknown) {
if (!(cause instanceof RegularFileCleanupFailure)) throw cause;
const cleanup = await retryRegularFileCleanup(cause, resources);
const primary =
cleanup.outcome.kind === "failed"
? cleanup.outcome.cause
: cause.cleanupCause;
throw configurationCleanupError(
`Could not safely access client configuration at ${cause.path}: ${errorMessage(primary)}`,
cause,
cleanup.cleanup,
);
}
});
} catch (cause: unknown) {
if (cause instanceof ArtifactReaderFailure)
throw configurationCleanupError(cause.message, cause, cause.cleanup);
throw cause;
}
};
const configurationCleanupError = (
message: string,
cause: unknown,
cleanup:
| { readonly reason: string; readonly resources: readonly string[] }
| undefined,
): ConfigurationError =>
new ConfigurationError(message, {
cause,
settings: [{ setting: "client configuration", constraint: message }],
...(cleanup === undefined ? {} : { cleanup }),
});
const errorMessage = (cause: unknown): string =>
cause instanceof Error ? cause.message : String(cause);
/** Detect supported agents from their config files or stable installation markers. */
export const detectClients = async (
home: string,
+2 -2
View File
@@ -312,8 +312,8 @@ const clientConfigurationDetail = (
.map(([name, value]) => `${name}=${value}`);
const environmentDetail =
entries.length === 0
? " No additional provider environment variables. Existing server environment overrides are retained."
: ` Detected provider environment: ${entries.join(", ")}. Existing server environment overrides are retained; detected values replace matching keys.`;
? " No additional environment variables."
: ` Environment: ${entries.join(", ")}.`;
const hopperDetail = installHopper
? environment.HOPPER_LAUNCHER_PATH === undefined
? " If this plan installs Hopper, REA will add HOPPER_LAUNCHER_PATH using the launcher path reported by that installation."
+85 -240
View File
@@ -4,7 +4,6 @@ import { isAbsolute } from "node:path";
import { z } from "zod";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { publishWebScripts } from "../browser/assets/PublishWebScripts.js";
import { selectScriptCapture } from "../browser/assets/ScriptCaptureAdapters.js";
import {
@@ -15,11 +14,9 @@ import {
} from "../domain/analysisErrorCore.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { err, ok, type Result } from "../domain/result.js";
import { safeParseJson } from "../domain/safeJson.js";
import {
@@ -29,11 +26,7 @@ import {
import { WebScriptExportError } from "../domain/webScriptExportError.js";
import type { ExecutionOptions } from "./AnalysisProvider.js";
import { WEB_SCRIPT_EXPORT_PROVIDER as PROVIDER } from "./InvestigationProviders.js";
import {
readRegularFile,
RegularFileCleanupFailure,
retryRegularFileCleanup,
} from "./RegularFileRead.js";
import { readRegularFile } from "./RegularFileRead.js";
import {
NonRegularFileReadError,
RegularFileChangedError,
@@ -41,29 +34,14 @@ import {
const OPERATION = "export_web_scripts";
interface CaptureRead {
readonly bytes: Buffer;
readonly cleanup?: {
readonly reason: string;
readonly incomplete: boolean;
readonly cause: unknown;
};
}
interface PreparedCapture {
readonly bytes: Buffer;
readonly loaded: ReturnType<typeof selectScriptCapture>;
}
/** Export one local capture through the shared CLI/MCP application workflow. */
export const exportWebScripts = async (
rawInput: unknown,
resources: ArtifactResourceScope,
options: ExecutionOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
const input = exportWebScriptsInputSchema.safeParse(rawInput);
return input.success
? exportWebScriptsValidated(input.data, resources, options)
? exportWebScriptsValidated(input.data, options)
: err(
analysisInputErrorFromIssues(OPERATION, input.error.issues, rawInput),
);
@@ -72,7 +50,6 @@ export const exportWebScripts = async (
/** Publish input already parsed by a named adapter contract. */
export const exportWebScriptsValidated = async (
input: ExportWebScriptsInput,
resources: ArtifactResourceScope,
options: ExecutionOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
if (!isAbsolute(input.capture_path) || !isAbsolute(input.output_directory))
@@ -88,19 +65,19 @@ export const exportWebScriptsValidated = async (
);
try {
options.signal?.throwIfAborted();
const prepared = await prepareCapture(
input.capture_path,
resources,
options.signal,
);
if (!prepared.ok) return prepared;
const { bytes, loaded } = prepared.value;
const read = await readCapture(input.capture_path, options.signal);
if (!read.ok) return read;
const bytes = read.value;
const loaded = parseCapture(bytes);
if (!loaded.ok) return loaded;
options.signal?.throwIfAborted();
const sha256 = createHash("sha256").update(bytes).digest("hex");
const result = await publishWebScripts(input, loaded, sha256, {
resources,
...(options.signal === undefined ? {} : { signal: options.signal }),
});
const result = await publishWebScripts(
input,
loaded.value,
sha256,
options.signal,
);
return ok(
createEvidence(
{ path: input.capture_path, sha256, format: "file" },
@@ -119,109 +96,55 @@ export const exportWebScriptsValidated = async (
limitations: result.limitations,
locations: [{ kind: "artifact-path", path: result.manifest.path }],
evidenceLinks:
loaded.sourceEvidenceId === null ? [] : [loaded.sourceEvidenceId],
loaded.value.sourceEvidenceId === null
? []
: [loaded.value.sourceEvidenceId],
},
),
);
} catch (cause: unknown) {
return err(mapExportFailure(cause, input, options.signal));
}
};
const prepareCapture = async (
path: string,
resources: ArtifactResourceScope,
signal: AbortSignal | undefined,
): Promise<Result<PreparedCapture, AnalysisError>> => {
const read = await resources.run(() => readCapture(path, resources, signal));
if (!read.ok) return read;
const cleanup = read.value.cleanup;
const loaded = parseCapture(
read.value.bytes,
cleanup === undefined || cleanup.incomplete
? undefined
: { cause: cleanup.cause },
);
if (!loaded.ok)
if (cause instanceof WebScriptExportError) return err(cause);
if (options.signal?.aborted === true)
return err(new AnalysisCancelledError(OPERATION));
if (cause instanceof ArtifactReaderFailure)
return err(
new WebScriptExportError(
cause.reason,
input.output_directory,
cause.message,
),
);
if (cause instanceof z.ZodError)
return err(new AnalysisOutputError(OPERATION, cause.message, { cause }));
if (
cause instanceof Error &&
"code" in cause &&
typeof cause.code === "string"
)
return err(
new WebScriptExportError(
"io",
`${input.capture_path} → ${input.output_directory}`,
cause.message,
),
);
return err(
cleanup?.incomplete === true
? incompleteCaptureCleanup(loaded.error, path, cleanup)
: loaded.error,
);
if (cleanup !== undefined) {
const primary = new WebScriptExportError(
"io",
path,
`Capture handle close failed: ${cleanup.reason}`,
{ cause: cleanup.cause },
);
return err(
cleanup.incomplete
? incompleteCaptureCleanup(primary, path, cleanup)
: primary,
new ProviderAdapterError(PROVIDER.id, OPERATION, {
cause,
diagnostics: {
capture_path: input.capture_path,
output_directory: input.output_directory,
error_name: cause instanceof Error ? cause.name : "UnknownError",
error_message:
cause instanceof Error
? cause.message
: typeof cause === "string"
? cause
: "Unknown script export failure",
},
}),
);
}
return ok({ bytes: read.value.bytes, loaded: loaded.value });
};
const mapExportFailure = (
cause: unknown,
input: ExportWebScriptsInput,
signal: AbortSignal | undefined,
): AnalysisError => {
if (cause instanceof WebScriptExportError) return cause;
if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined)
return analysisErrorWithCleanupFailure(
new WebScriptExportError(
cause.reason,
input.output_directory,
cause.message,
{ cause },
),
new ProviderCleanupError(
PROVIDER.id,
cause.cleanup.resources,
{ reason: cause.cleanup.reason },
{ cause, operation: OPERATION },
),
OPERATION,
);
if (signal?.aborted === true)
return new AnalysisCancelledError(OPERATION, { cause });
if (cause instanceof ArtifactReaderFailure)
return new WebScriptExportError(
cause.reason,
input.output_directory,
cause.message,
{ cause },
);
if (cause instanceof z.ZodError)
return new AnalysisOutputError(OPERATION, cause.message, { cause });
if (
cause instanceof Error &&
"code" in cause &&
typeof cause.code === "string"
)
return new WebScriptExportError(
"io",
`${input.capture_path} → ${input.output_directory}`,
cause.message,
{ cause },
);
return new ProviderAdapterError(PROVIDER.id, OPERATION, {
cause,
diagnostics: {
capture_path: input.capture_path,
output_directory: input.output_directory,
error_name: cause instanceof Error ? cause.name : "UnknownError",
error_message:
cause instanceof Error
? cause.message
: typeof cause === "string"
? cause
: "Unknown script export failure",
},
});
};
/**
@@ -230,115 +153,45 @@ const mapExportFailure = (
*/
const readCapture = async (
path: string,
resources: ArtifactResourceScope,
signal: AbortSignal | undefined,
): Promise<Result<CaptureRead, AnalysisError>> => {
): Promise<Result<Buffer, AnalysisError>> => {
try {
return ok({ bytes: await readRegularFile(path, { signal }) });
return ok(await readRegularFile(path, { signal }));
} catch (cause: unknown) {
if (cause instanceof RegularFileCleanupFailure) {
const retry = await retryRegularFileCleanup(cause, resources);
const cleanup = {
reason: retry.cleanup?.reason ?? errorMessage(cause.cleanupCause),
incomplete: retry.cleanup !== undefined,
cause: cause.cleanupCause,
};
if (cause.outcome.kind === "completed")
return ok({ bytes: cause.outcome.value as Buffer, cleanup });
const primary = captureReadFailure(
path,
cause.outcome.cause,
signal,
retry.cleanup === undefined ? { cause: cause.cleanupCause } : undefined,
);
const code =
cause instanceof Error && "code" in cause ? String(cause.code) : "";
if (code === "EACCES" || code === "EPERM")
return err(
retry.cleanup === undefined
? primary
: incompleteCaptureCleanup(primary, path, cleanup),
new AnalysisAccessDeniedError(OPERATION, path, code, { cause }),
);
}
return err(captureReadFailure(path, cause, signal));
if (
cause instanceof NonRegularFileReadError ||
cause instanceof RegularFileChangedError ||
code === "ENOENT" ||
code === "ENOTDIR" ||
code === "EISDIR" ||
code === "ENXIO"
)
return err(
new AnalysisInputError(OPERATION, { cause }, [
{
path: ["capture_path"],
reason: "invalid_value",
message:
cause instanceof NonRegularFileReadError && code !== "EISDIR"
? cause.message
: code === "EISDIR"
? `Selected capture is a directory, not a file: ${path}`
: `Selected capture could not be read (${code}): ${path}`,
},
]),
);
throw cause;
}
};
const captureReadFailure = (
path: string,
cause: unknown,
signal: AbortSignal | undefined,
closeFailure?: { readonly cause: unknown },
): AnalysisError => {
const causeWithClose =
closeFailure === undefined
? cause
: new AggregateError(
[cause, closeFailure.cause],
"Capture read and file-handle close both failed",
{ cause },
);
if (signal?.aborted === true)
return new AnalysisCancelledError(OPERATION, { cause: causeWithClose });
const code =
cause instanceof Error && "code" in cause ? String(cause.code) : "";
if (code === "EACCES" || code === "EPERM")
return new AnalysisAccessDeniedError(OPERATION, path, code, {
cause: causeWithClose,
});
if (
cause instanceof NonRegularFileReadError ||
cause instanceof RegularFileChangedError ||
code === "ENOENT" ||
code === "ENOTDIR" ||
code === "EISDIR" ||
code === "ENXIO"
)
return new AnalysisInputError(OPERATION, { cause: causeWithClose }, [
{
path: ["capture_path"],
reason: "invalid_value",
message:
cause instanceof NonRegularFileReadError && code !== "EISDIR"
? cause.message
: code === "EISDIR"
? `Selected capture is a directory, not a file: ${path}`
: `Selected capture could not be read (${code}): ${path}`,
},
]);
if (code !== "")
return new WebScriptExportError("io", path, errorMessage(cause), {
cause: causeWithClose,
});
return new ProviderAdapterError(PROVIDER.id, OPERATION, {
cause: causeWithClose,
diagnostics: {
capture_path: path,
error_name: cause instanceof Error ? cause.name : "UnknownError",
error_message: cause instanceof Error ? cause.message : String(cause),
},
});
};
const incompleteCaptureCleanup = (
primary: AnalysisError,
path: string,
cleanup: NonNullable<CaptureRead["cleanup"]>,
): AnalysisError =>
analysisErrorWithCleanupFailure(
primary,
new ProviderCleanupError(
PROVIDER.id,
[path],
{ reason: cleanup.reason },
{ cause: cleanup.cause, operation: OPERATION },
),
OPERATION,
);
const errorMessage = (cause: unknown): string =>
cause instanceof Error ? cause.message : String(cause);
const parseCapture = (
bytes: Buffer,
closeFailure?: { readonly cause: unknown },
): Result<ReturnType<typeof selectScriptCapture>, AnalysisError> => {
try {
const text = new TextDecoder("utf-8", {
@@ -349,16 +202,8 @@ const parseCapture = (
if (!json.ok) throw new TypeError(json.error);
return ok(selectScriptCapture(json.value));
} catch (cause: unknown) {
const causeWithClose =
closeFailure === undefined
? cause
: new AggregateError(
[cause, closeFailure.cause],
"Capture parse and file-handle close both failed",
{ cause },
);
return err(
new AnalysisInputError(OPERATION, { cause: causeWithClose }, [
new AnalysisInputError(OPERATION, { cause }, [
{
path: ["capture_path"],
reason: "invalid_format",
@@ -2,11 +2,11 @@ import { setImmediate } from "node:timers";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { analyzeJavaScriptApplication } from "../../support/javascriptApplicationScope.js";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import { analyzeJavaScriptApplication } from "./JavaScriptApplicationService.js";
describe("JavaScript application cancellation", () => {
describe("JavaScript analysis cancellation before publication", () => {
it("interrupts semantic graph commitment before result validation", async () => {
const root = await createTestTempDirectory("rea-js-cancel-semantic-");
await writeFile(
@@ -33,9 +33,7 @@ describe("JavaScript application cancellation", () => {
},
);
if (result.ok)
throw new Error(
"Cancelled commitment must not publish a successful analysis",
);
throw new Error("Cancelled commitment must not publish Evidence");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "cancelled",
details: { reason: "cancelled" },
@@ -44,7 +42,7 @@ describe("JavaScript application cancellation", () => {
expect(phases).not.toContain("validate_javascript_application_result");
});
it("honors control turns and cancellation while preparing one large source for owned analysis (#1462)", async () => {
it("handles control turns and cancellation inside one large source file (#1462)", async () => {
const root = await createTestTempDirectory("rea-js-cancel-in-file-");
await writeFile(
join(root, "index.js"),
@@ -76,7 +74,7 @@ describe("JavaScript application cancellation", () => {
},
},
);
if (result.ok) throw new Error("Cancelled analysis must not succeed");
if (result.ok) throw new Error("Cancelled analysis must not publish");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "cancelled",
});
@@ -120,21 +118,12 @@ describe("JavaScript application cancellation", () => {
},
);
expect(requested).toBe(true);
if (result.ok) throw new Error("Cancelled analysis must return a failure");
const failure = projectAnalysisError(result.error);
expect(failure).toMatchObject({ code: "cancelled" });
if (phase === "parse_javascript_source")
expect(failure).toMatchObject({
details: {
operation: "analyze_javascript_application",
cleanup: "complete",
partial_observation: {
normalized_result: {
statistics: { relevant_files: 1, parse_failures: 0 },
},
},
},
});
if (result.ok)
throw new Error("Cancelled analysis must not publish Evidence");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "cancelled",
details: { reason: "cancelled" },
});
expect(terminal).toEqual([]);
});
@@ -10,7 +10,7 @@ import { javascriptApplicationAnalysisResultSchema } from "../../domain/javascri
import { matchJavaScriptApplicationVersions } from "../../domain/javascript/javascriptApplicationVersionKeys.js";
import { findApplicationFeatureSeeds } from "../../domain/javascript/javascriptFeatureSeed.js";
import { traceApplicationFeatureInputSchema } from "../../domain/javascript/javascriptFeatureTraceSchemas.js";
import { analyzeJavaScriptApplication } from "../../../tests/support/javascriptApplicationScope.js";
import { analyzeJavaScriptApplication } from "./JavaScriptApplicationService.js";
const analyzeSource = async (
source: string,
@@ -5,7 +5,7 @@ import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { javascriptApplicationAnalysisResultSchema } from "../../domain/javascript/javascriptApplicationAnalysis.js";
import { analyzeJavaScriptApplication } from "../../../tests/support/javascriptApplicationScope.js";
import { analyzeJavaScriptApplication } from "./JavaScriptApplicationService.js";
it.each([
{
@@ -4,11 +4,9 @@ import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
import { scanCanonicalArtifactInventory } from "../../../tests/fixtures/artifactInventory.js";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import { analyzeJavaScriptApplication } from "../../../tests/support/javascriptApplicationScope.js";
import { analyzeJavaScriptApplication } from "./JavaScriptApplicationService.js";
describe("JavaScript application failure diagnostics", () => {
it("identifies the rejected result field in caller-visible diagnostics", async () => {
@@ -155,41 +153,3 @@ describe("JavaScript application failure diagnostics", () => {
},
);
});
describe("JavaScript application cleanup diagnostics", () => {
it("preserves cleanup and a complete inventory when translating reader failures", async () => {
const inputPath = await createTestTempDirectory("rea-js-cleanup-failure-");
await writeFile(join(inputPath, "main.js"), "export const value = 1;\n");
const inventory = await scanCanonicalArtifactInventory(inputPath);
const cleanup = {
reason: "reader remains open",
resources: [`JavaScript artifact reader for ${inputPath}`],
};
const partialObservation = {
kind: "artifact-inventory" as const,
inventory,
};
const failure = new ArtifactReaderFailure("io", "Reader cleanup failed", {
cleanup,
partialObservation,
});
const result = await analyzeJavaScriptApplication(
{ input_path: inputPath, format: "directory" },
{
progress: {
report: async () => {
throw failure;
},
},
},
);
if (result.ok) throw new Error("Expected reader failure");
expect(result.error).toMatchObject({
_tag: "ArtifactOperationError",
cleanup,
partialObservation,
});
});
});
@@ -1,14 +1,18 @@
import { z } from "zod";
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
import type { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
import {
analyzeJavaScriptApplicationInputSchema,
parseOwnedJavaScriptApplicationAnalysisSteps,
} from "../../domain/javascript/javascriptApplicationAnalysis.js";
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import {
AnalysisAccessDeniedError,
AnalysisInputError,
AnalysisOutputError,
AnalysisUnsupportedTargetError,
} from "../../domain/analysisErrorCore.js";
import { ArtifactOperationError } from "../../domain/artifactOperationError.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import { type AnalysisError } from "../../domain/analysisErrorBase.js";
import type { Evidence } from "../../domain/evidence.js";
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
import { err, ok, type Result } from "../../domain/result.js";
@@ -28,7 +32,6 @@ const OPERATION = "analyze_javascript_application" as const;
/** Statically analyze one local JavaScript/Electron application. */
export const analyzeJavaScriptApplication = async (
rawInput: unknown,
scope: ArtifactResourceScope,
options: ExecutionOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
const parsed = analyzeJavaScriptApplicationInputSchema.safeParse(rawInput);
@@ -36,13 +39,12 @@ export const analyzeJavaScriptApplication = async (
return err(
analysisInputErrorFromIssues(OPERATION, parsed.error.issues, rawInput),
);
return analyzeJavaScriptApplicationValidated(parsed.data, scope, options);
return analyzeJavaScriptApplicationValidated(parsed.data, options);
};
/** Analyze input already parsed by a trusted adapter boundary. */
export const analyzeJavaScriptApplicationValidated = async (
input: z.output<typeof analyzeJavaScriptApplicationInputSchema>,
scope: ArtifactResourceScope,
options: ExecutionOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
try {
@@ -59,14 +61,7 @@ export const analyzeJavaScriptApplicationValidated = async (
input_path: input.input_path,
format: input.format,
integrity_policy: input.integrity_policy,
...(input.max_heap_mb === undefined
? {}
: { max_heap_mb: input.max_heap_mb }),
...(input.analysis_timeout_ms === undefined
? {}
: { analysis_timeout_ms: input.analysis_timeout_ms }),
},
scope,
options.signal,
options.progress,
);
@@ -111,10 +106,22 @@ export const analyzeJavaScriptApplicationValidated = async (
assertJavaScriptAnalysisActive(options.signal);
return ok(evidence);
} catch (cause: unknown) {
// Preserve execution constraints and their completed partial Evidence.
if (cause instanceof AnalysisError) return err(cause);
// Input selection failures are already typed by their cause.
if (
cause instanceof AnalysisInputError ||
cause instanceof AnalysisUnsupportedTargetError ||
cause instanceof AnalysisAccessDeniedError
)
return err(cause);
if (cause instanceof ArtifactReaderFailure)
return err(artifactFailureToOperationError(cause));
return err(
new ArtifactOperationError(
OPERATION,
cause.reason,
cause.details,
cause.message,
),
);
if (cause instanceof z.ZodError)
return err(
new AnalysisOutputError(OPERATION, describeResultSchemaFailure(cause), {
@@ -146,23 +153,6 @@ export const analyzeJavaScriptApplicationValidated = async (
}
};
const artifactFailureToOperationError = (
cause: ArtifactReaderFailure,
): ArtifactOperationError =>
new ArtifactOperationError(
OPERATION,
cause.reason,
cause.details,
cause.message,
{
cause,
...(cause.cleanup === undefined ? {} : { cleanup: cause.cleanup }),
...(cause.partialObservation === undefined
? {}
: { partialObservation: cause.partialObservation }),
},
);
const describeResultSchemaFailure = (cause: z.ZodError): string => {
const issue = cause.issues[0];
if (issue === undefined) return "Result schema rejected an unknown issue";
@@ -7,7 +7,7 @@ import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirect
import { javascriptApplicationAnalysisResultSchema } from "../../domain/javascript/javascriptApplicationAnalysis.js";
import { javaScriptSemanticQueryResultSchema } from "../../domain/javascript/javascriptSemanticQuerySchemas.js";
import { queryJavaScriptSemanticGraph } from "../../domain/javascript/javascriptSemanticQuery.js";
import { analyzeJavaScriptApplication } from "../../../tests/support/javascriptApplicationScope.js";
import { analyzeJavaScriptApplication } from "./JavaScriptApplicationService.js";
it.each([
{
@@ -5,7 +5,7 @@ import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { javascriptApplicationAnalysisResultSchema } from "../../domain/javascript/javascriptApplicationAnalysis.js";
import { analyzeJavaScriptApplication } from "../../../tests/support/javascriptApplicationScope.js";
import { analyzeJavaScriptApplication } from "./JavaScriptApplicationService.js";
const graphIdentities = async (source: string) => {
const inputPath = await createTestTempDirectory("rea-js-template-literal-");
@@ -7,7 +7,7 @@ import { canonicalJson } from "../../domain/comparisonSemantics.js";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { javascriptApplicationAnalysisResultSchema } from "../../domain/javascript/javascriptApplicationAnalysis.js";
import { parseJavaScriptSource } from "../../domain/javascript/javascriptSourceParser.js";
import { analyzeJavaScriptApplication } from "../../../tests/support/javascriptApplicationScope.js";
import { analyzeJavaScriptApplication } from "./JavaScriptApplicationService.js";
type ApplicationAnalysis = ReturnType<
typeof javascriptApplicationAnalysisResultSchema.parse
@@ -7,6 +7,7 @@ import type { ApplicationVersionComparisonResult } from "../../domain/javascript
import type { JavaScriptExportShapeComparisonResult } from "../../domain/javascript/javascriptExportShapeComparisonSchemas.js";
import type { ApplicationFeatureTraceResult } from "../../domain/javascript/javascriptFeatureTraceSchemas.js";
import type { JavaScriptSemanticTraceResult } from "../../domain/javascript/javascriptSemanticTraceSchemas.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import type { SourceToBundleComparisonResult } from "../../domain/javascript/sourceToBundleComparisonSchemas.js";
import { JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER } from "../InvestigationProviders.js";
@@ -19,7 +20,7 @@ export const createApplicationFeatureTraceEvidence = (
predicateType: "rea.application-feature-trace",
operation: "trace_application_feature",
parameters,
result,
result: jsonValueSchema.parse(result),
rawResult: null,
confidence: "inferred",
authority: "analyst-inference",
@@ -37,7 +38,7 @@ export const createJavaScriptSemanticTraceEvidence = (
predicateType: "rea.javascript-semantic-trace",
operation: "trace_javascript_semantics",
parameters,
result,
result: jsonValueSchema.parse(result),
rawResult: null,
confidence: "inferred",
authority: "analyst-inference",
@@ -55,7 +56,7 @@ export const createApplicationVersionComparisonEvidence = (
predicateType: "rea.application-version-comparison",
operation: "compare_application_versions",
parameters,
result,
result: jsonValueSchema.parse(result),
rawResult: null,
confidence: "inferred",
authority: "analyst-inference",
@@ -73,7 +74,7 @@ export const createSourceToBundleComparisonEvidence = (
predicateType: "rea.source-to-bundle-comparison",
operation: "compare_source_to_bundle",
parameters,
result,
result: jsonValueSchema.parse(result),
rawResult: null,
confidence: "inferred",
authority: "analyst-inference",
@@ -91,7 +92,7 @@ export const createJavaScriptExportShapeComparisonEvidence = (
predicateType: "rea.javascript-export-shape-comparison",
operation: "compare_javascript_export_shapes",
parameters,
result,
result: jsonValueSchema.parse(result),
rawResult: null,
confidence: "inferred",
authority: "analyst-inference",
@@ -8,7 +8,6 @@ import {
classifyParsedJavaScriptOpenReceiversSteps,
} from "../../domain/javascript/javascriptSemanticAnalysis.js";
import type { JavaScriptSemanticIr } from "../../domain/javascript/javascriptSemanticIr.js";
import { projectJavaScriptModuleSemantics } from "../../domain/javascript/javascriptModuleSemanticIr.js";
import { parseJavaScriptSource } from "../../domain/javascript/javascriptSourceParser.js";
import { hasValidSourceMapContents } from "../../domain/sourceMapContents.js";
import { flattenSourceMapLeaves } from "../../domain/sourceMapEnvelope.js";
@@ -36,15 +35,6 @@ import type {
import { analyzeJavaScriptJsonModule } from "./JavaScriptJsonModules.js";
import { completeJavaScriptAnalysisSteps } from "./JavaScriptAnalysisControl.js";
import { htmlArtifactReferences } from "../../domain/javascript/htmlArtifactReferences.js";
import type { JavaScriptSourceAnalysisPort } from "../../domain/javascript/javascriptSourceAnalysis.js";
import type { JavaScriptSemanticGraphProjection } from "./JavaScriptSemanticGraphBuilder.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import {
AnalysisCancelledError,
AnalysisResourceConstraintError,
AnalysisTimeoutError,
} from "../../domain/analysisErrorCore.js";
interface MutableArtifactAnalysis<
SemanticIr extends JavaScriptModuleSemanticIr,
@@ -105,7 +95,27 @@ export const analyzeAndProjectJavaScriptArtifactFiles = async (
): Generator<void, JavaScriptModuleSemanticIr> {
const projection = projectSemantics(file, ir);
if (projection !== undefined) while (projection.next().done !== true) yield;
return projectJavaScriptModuleSemantics(ir);
const programScopes = ir.scopes.filter(({ kind }) => kind === "program");
const programScopeId = programScopes[0]?.scopeId;
const localNames = new Set(
ir.moduleLinks.map(({ localName }) => localName),
);
const callableIds = new Set(
ir.moduleLinks.map(({ callableId }) => callableId),
);
return {
scopes: programScopes,
bindings: ir.bindings.filter(
({ name, scopeId }) =>
scopeId === programScopeId && localNames.has(name),
),
callables: ir.callables.filter(({ callableId }) =>
callableIds.has(callableId),
),
moduleLinks: ir.moduleLinks,
coverage: ir.coverage,
limitations: ir.limitations,
};
};
const context = { state, projectSemantics: projectFileSemantics };
for (const [index, file] of fileSet.files.entries()) {
@@ -120,174 +130,6 @@ export const analyzeAndProjectJavaScriptArtifactFiles = async (
return finalizeArtifactAnalysis(state);
};
/** Analyze sources behind a hard heap boundary, retaining collected facts on interruption. */
export const analyzeAndAdoptJavaScriptArtifactFiles = async (
fileSet: JavaScriptArtifactFileSet,
worker: Pick<JavaScriptSourceAnalysisPort, "analyze">,
projection: JavaScriptSemanticGraphProjection,
beforeFile: (
file: JavaScriptArtifactFile,
completed: number,
total: number,
) => Promise<void>,
signal?: AbortSignal,
): Promise<{
readonly analysis: JavaScriptModuleArtifactAnalysis;
readonly interruption: AnalysisError | null;
}> => {
const state = emptyArtifactAnalysis<JavaScriptModuleSemanticIr>();
let interruption: AnalysisError | null = null;
for (const [index, file] of fileSet.files.entries()) {
try {
await setImmediate();
await beforeFile(file, index, fileSet.files.length);
if (signal?.aborted === true)
throw new AnalysisCancelledError("analyze_javascript_application");
if (file.kind !== "javascript" || !file.text.included) {
const steps = analyzeArtifactFileSteps(file, {
state,
projectSemantics: function* (_file, ir) {
yield;
return projectJavaScriptModuleSemantics(ir);
},
});
await completeJavaScriptAnalysisSteps(steps, signal);
continue;
}
const result = await worker.analyze(
file,
projection.remainingFileNodeBudget(),
signal,
);
const facts = result.ok ? result.value : result.error;
const applicationProjectionFailure = facts.applicationProjectionFailure;
if (facts.projection !== null)
projection.adoptFileProjection(facts.projection);
const error = result.ok ? null : result.error.error;
const limits =
error instanceof AnalysisResourceConstraintError
? error.reportedLimits
: error instanceof AnalysisTimeoutError
? { worker_timeout_ms: error.timeoutMs }
: null;
const failure =
error === null
? undefined
: {
reason: `${file.path}: ${error.message}`,
error: projectAnalysisError(error),
limits,
};
state.files.push({
file,
javascript: facts.javascript,
semantic: facts.module === null ? null : { ir: facts.module },
...(failure === undefined ? {} : { analysis_failure: failure }),
...(applicationProjectionFailure === undefined
? {}
: {
application_projection_failure: {
reason: applicationProjectionFailure.message,
error: projectAnalysisError(applicationProjectionFailure),
limits: applicationProjectionFailure.reportedLimits,
},
}),
});
if (failure !== undefined && facts.projection === null)
projection.recordUnavailableFile(
file,
failure.reason,
failure.limits,
error instanceof AnalysisResourceConstraintError ||
error instanceof AnalysisTimeoutError
? "resource-limit"
: "incomplete-module",
);
if (facts.javascript !== null) {
state.visitedNodes += facts.javascript.visited_ast_nodes;
state.findings +=
findingCount(facts.javascript) +
(facts.module?.moduleLinks.length ?? 0);
state.modules += facts.javascript.bundler_registrations.reduce(
(count, item) => count + item.modules.length,
0,
);
if (facts.javascript.parse_status === "failed")
state.parseFailures += 1;
}
if (
error !== null &&
(!(error instanceof AnalysisResourceConstraintError) ||
error.reportedLimits?.parent_result_budget_exhausted === true)
) {
interruption = error;
break;
}
} catch (cause: unknown) {
if (signal?.aborted !== true && !(cause instanceof AnalysisError))
throw cause;
interruption =
signal?.aborted === true
? new AnalysisCancelledError("analyze_javascript_application")
: cause instanceof AnalysisError
? cause
: null;
if (interruption !== null) {
state.files.push({
file,
javascript: null,
semantic: null,
analysis_failure: {
reason: `${file.path}: ${interruption.message}`,
error: projectAnalysisError(interruption),
limits: null,
},
});
projection.recordUnavailableFile(
file,
interruption.message,
null,
"incomplete-module",
);
}
break;
}
}
if (interruption !== null) {
const analyzedPaths = new Set(state.files.map(({ file }) => file.path));
const failure = {
reason: `Source analysis was interrupted: ${interruption.message}`,
error: projectAnalysisError(interruption),
limits:
interruption instanceof AnalysisResourceConstraintError
? interruption.reportedLimits
: interruption instanceof AnalysisTimeoutError
? { worker_timeout_ms: interruption.timeoutMs }
: null,
};
for (const file of fileSet.files) {
if (analyzedPaths.has(file.path)) continue;
state.files.push({
file,
javascript: null,
semantic: null,
analysis_failure: failure,
});
if (file.kind === "javascript")
projection.recordUnavailableFile(
file,
failure.reason,
failure.limits,
interruption instanceof AnalysisResourceConstraintError ||
interruption instanceof AnalysisTimeoutError
? "resource-limit"
: "incomplete-module",
);
}
}
return { analysis: finalizeArtifactAnalysis(state), interruption };
};
const analyzeArtifactFiles = <SemanticIr extends JavaScriptModuleSemanticIr>(
fileSet: JavaScriptArtifactFileSet,
projectSemantics: ArtifactAnalysisContext<SemanticIr>["projectSemantics"],
@@ -319,12 +161,6 @@ const finalizeArtifactAnalysis = <
limitations: [
"JavaScript and HTML were parsed as inert text; bundle bootstrap code was never executed.",
"Static paths and relationships may remain unresolved when expressions are dynamic or obfuscated.",
...state.files.flatMap(
({ analysis_failure, application_projection_failure }) =>
[analysis_failure, application_projection_failure].flatMap(
(failure) => (failure === undefined ? [] : [failure.reason]),
),
),
],
};
};
@@ -4,9 +4,7 @@ import type {
JavaScriptStaticAnalysis,
} from "../../domain/javascript/javascriptStaticAnalysisTypes.js";
import type { JavaScriptSemanticIr } from "../../domain/javascript/javascriptSemanticIr.js";
import type { JavaScriptModuleSemanticIr } from "../../domain/javascript/javascriptModuleSemanticIr.js";
import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
import type { JsonValue } from "../../domain/jsonValue.js";
interface JavaScriptStructuredObservation {
readonly path: string;
@@ -91,7 +89,15 @@ export type JavaScriptJsonModuleObservation = JavaScriptStructuredObservation &
);
/** Module facts needed after file-local semantic projection has finished. */
export type { JavaScriptModuleSemanticIr } from "../../domain/javascript/javascriptModuleSemanticIr.js";
export type JavaScriptModuleSemanticIr = Pick<
JavaScriptSemanticIr,
| "scopes"
| "bindings"
| "callables"
| "moduleLinks"
| "coverage"
| "limitations"
>;
/** One relevant file plus optional AST-only JavaScript facts. */
export interface AnalyzedJavaScriptArtifactFile<
@@ -102,18 +108,6 @@ export interface AnalyzedJavaScriptArtifactFile<
readonly semantic: {
readonly ir: SemanticIr;
} | null;
/** Operational incompleteness, distinct from a malformed source file. */
readonly analysis_failure?: {
readonly reason: string;
readonly error: JsonValue;
readonly limits: Readonly<Record<string, JsonValue>> | null;
};
/** Facts retained inline when their expanded graph exceeds available memory. */
readonly application_projection_failure?: {
readonly reason: string;
readonly error: JsonValue;
readonly limits: Readonly<Record<string, JsonValue>> | null;
};
}
/** Complete static-analysis projection before graph construction. */
@@ -12,7 +12,7 @@ export class JavaScriptArtifactGraphAccumulator {
readonly #nodes = new Map<string, ApplicationNode>();
readonly #edges = new Map<string, ApplicationEdge>();
/** Create or merge one canonical node, retaining a stable live construction reference. */
/** Create or merge one canonical node. */
addNode<Input extends DisplayableNodeInput>(input: Input): ApplicationNode {
const created = createJavaScriptApplicationNode(displayableNode(input));
const existing = this.#nodes.get(created.node_id);
@@ -23,23 +23,19 @@ export class JavaScriptArtifactGraphAccumulator {
const bySemanticId = new Map(
[...existing.observations, ...created.observations].map((observation) => [
observation.observation_id,
observation,
observationInput(observation),
]),
);
const observations = [...bySemanticId.values()].sort((left, right) =>
left.observation_id < right.observation_id
? -1
: left.observation_id > right.observation_id
? 1
: 0,
);
// Both factories already validated and identified these observations.
// Replacing the node retained every previous observation array through
// path/chunk/IPC indexes when multiple paths shared an entity identity.
existing.observations.length = 0;
for (const observation of observations)
existing.observations.push(observation);
return existing;
const observations = [...bySemanticId.entries()]
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
.map(([, observation]) => observation);
const merged = createJavaScriptApplicationNode({
kind: existing.kind,
identity: existing.identity,
observations,
});
this.#nodes.set(merged.node_id, merged);
return merged;
}
/** Create or replace one canonical edge by semantic identifier. */
@@ -60,6 +56,17 @@ export class JavaScriptArtifactGraphAccumulator {
}
}
const observationInput = (
observation: ApplicationNode["observations"][number],
) => {
const {
observation_id: _observationId,
identifier_strategy: _strategy,
...input
} = observation;
return input;
};
/** Node fields whose display form is normalized before validation. */
interface DisplayableNodeInput {
readonly observations: readonly { readonly label: string | null }[];
@@ -107,33 +107,19 @@ function* buildJavaScriptArtifactGraphInputSteps(
yield;
addJavaScriptArtifactFiles(context);
yield;
// Raw observations remain on the file nodes. Only admitted expansions feed
// the relationship builders, including their Electron and bundler callers.
const projectionContext = {
...context,
analysis: {
...analysis,
files: analysis.files.map((file) =>
file.application_projection_failure === undefined
? file
: { ...file, javascript: null, semantic: null },
),
},
};
const packageRoots = addJavaScriptPackageNodes(projectionContext);
const packageRoots = addJavaScriptPackageNodes(context);
yield;
addJavaScriptSourceModules(projectionContext);
addJavaScriptSourceModules(context);
yield;
const bundlerLimitations = addJavaScriptBundlerNodes(projectionContext);
const bundlerLimitations = addJavaScriptBundlerNodes(context);
const relationshipOmissions =
yield* addJavaScriptModuleRelationshipsSteps(projectionContext);
const findingLimitations =
yield* addJavaScriptStaticFindingsSteps(projectionContext);
addElectronBoundaries(projectionContext);
yield* addJavaScriptModuleRelationshipsSteps(context);
const findingLimitations = yield* addJavaScriptStaticFindingsSteps(context);
addElectronBoundaries(context);
yield;
addJavaScriptHtmlRoles(projectionContext);
addJavaScriptHtmlRoles(context);
yield;
addJavaScriptSourceMapOriginals(projectionContext);
addJavaScriptSourceMapOriginals(context);
yield;
const coverage = graphCoverage(context);
return {
@@ -167,34 +153,14 @@ const graphCoverage = (context: JavaScriptArtifactGraphContext) => {
javascript !== null && javascript.parse_status === "partial",
);
const unknownGap =
context.analysis.files.some(
({ analysis_failure, application_projection_failure }) =>
analysis_failure !== undefined ||
application_projection_failure !== undefined,
) ||
context.analysis.parse_failures > 0 ||
context.fileSet.invalid_utf8_files > 0 ||
sourceMapPolicyGap ||
malformedStructuredData ||
partialJavaScript;
const executionLimits = context.analysis.files.flatMap(
({ analysis_failure, application_projection_failure }) =>
[analysis_failure, application_projection_failure].flatMap((failure) =>
failure === undefined
? []
: javaScriptAnalysisCoverageLimits(failure.limits),
),
);
if (resourceLimits.length > 0 || executionLimits.length > 0)
if (resourceLimits.length > 0)
return partialApplicationCoverage(
[
...new Map(
[
...semanticResourceLimitCoverage(resourceLimits),
...executionLimits,
].map((limit) => [JSON.stringify(limit), limit]),
).values(),
],
semanticResourceLimitCoverage(resourceLimits),
null,
);
if (unknownGap) return partialApplicationCoverage([], null);
@@ -294,4 +260,3 @@ const graphLimitations = (
]),
];
};
import { javaScriptAnalysisCoverageLimits } from "../../domain/javascript/javascriptAnalysisResourceControls.js";
@@ -1,5 +1,4 @@
import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySnapshot.js";
import type { JsonValue } from "../../domain/jsonValue.js";
import { compositeKey } from "../../domain/unicodeCodePointOrder.js";
import {
completeApplicationCoverage,
@@ -100,8 +99,6 @@ export interface UnavailableParseInput {
readonly asset: ApplicationNode;
readonly operation: string;
readonly limitation: string;
readonly failure?: JsonValue;
readonly limits?: JavaScriptArtifactGraphCoverage["limits"];
}
/** Add a direct artifact-containment edge. */
@@ -185,15 +182,12 @@ export const addUnavailableStaticParseScope = (
path: input.file.path,
operation: input.operation,
limitation: input.limitation,
...(input.failure === undefined
? {}
: { analysis_failure: input.failure }),
},
evidence: unavailableAstEvidence({
sha256: input.file.sha256,
path: input.file.path,
operation: input.operation,
coverage: partialApplicationCoverage(input.limits ?? [], null),
coverage: partialApplicationCoverage([], null),
limitation: input.limitation,
}),
},
@@ -2,9 +2,6 @@ import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySn
import type { ApplicationNode } from "../../domain/javascript/javascriptApplicationGraphSchemas.js";
import { completeApplicationCoverage } from "../../domain/javascript/javascriptApplicationEvidenceSchemas.js";
import type { JavaScriptModuleArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import { freezeJsonSnapshot } from "../../domain/immutableJson.js";
import type { JavaScriptSourceRange } from "../../domain/javascript/javascriptStaticAnalysisTypes.js";
import type {
JavaScriptArtifactContainer,
JavaScriptArtifactFile,
@@ -15,14 +12,12 @@ import {
addUnavailableStaticParseScope,
artifactFileNodeKind,
artifactLocalIdentity,
javascriptAnalysisCoverage,
createElectronRoleNode,
linkElectronRoleToAsset,
type JavaScriptArtifactGraphContext,
} from "./JavaScriptArtifactGraphContext.js";
import {
artifactObservationEvidence,
astObservationEvidence,
staticInferenceEvidence,
} from "./JavaScriptArtifactGraphEvidence.js";
import { resolveArtifactPathByContext } from "./JavaScriptArtifactPathResolution.js";
@@ -120,52 +115,9 @@ export const addJavaScriptArtifactContainers = (
export const addJavaScriptArtifactFiles = (
context: JavaScriptArtifactGraphContext,
): void => {
const packagesByPath = indexFirstByPath(context.analysis.packages);
const jsonModulesByPath = indexFirstByPath(context.analysis.json_modules);
const sourceMapsByPath = indexFirstByPath(context.analysis.source_maps);
for (const analyzed of context.analysis.files) {
const { file } = analyzed;
const jsonValue = jsonModulesByPath.get(file.path);
const target = createFileTarget(
context,
file,
analyzed.javascript,
jsonValue,
);
if (
analyzed.application_projection_failure !== undefined &&
analyzed.javascript !== null
)
context.accumulator.addNode({
kind: target.kind,
identity: target.identity,
observations: [
{
label: file.path,
properties: {
static_analysis: freezeJsonSnapshot(
jsonValueSchema.parse(analyzed.javascript),
),
semantic_module_analysis:
analyzed.semantic === null
? null
: freezeJsonSnapshot(
jsonValueSchema.parse(analyzed.semantic.ir),
),
application_projection_failure:
analyzed.application_projection_failure.error,
},
evidence: astObservationEvidence({
sha256: file.sha256,
path: file.path,
operation: "retain-unexpanded-static-findings",
range: sourceFileRange(file),
coverage: javascriptAnalysisCoverage(analyzed.javascript),
limitations: [analyzed.application_projection_failure.reason],
}),
},
],
});
const target = createFileTarget(context, file, analyzed.javascript);
context.fileNodes.set(file.path, target);
if (file.kind === "javascript") context.assetNodes.set(file.path, target);
const entry = createAsarEntry(context, file);
@@ -198,18 +150,7 @@ export const addJavaScriptArtifactFiles = (
}),
});
}
if (analyzed.analysis_failure !== undefined)
addUnavailableStaticParseScope(context, {
file,
asset: target,
operation: "analyze-javascript-source",
limitation: analyzed.analysis_failure.reason,
failure: analyzed.analysis_failure.error,
limits: javaScriptAnalysisCoverageLimits(
analyzed.analysis_failure.limits,
),
});
else if (
if (
file.kind === "javascript" &&
(analyzed.javascript === null ||
analyzed.javascript.parse_status === "failed")
@@ -222,18 +163,9 @@ export const addJavaScriptArtifactFiles = (
? "JavaScript syntax could not be parsed."
: `JavaScript text was unavailable: ${file.text.reason}.`,
});
if (analyzed.application_projection_failure !== undefined)
addUnavailableStaticParseScope(context, {
file,
asset: target,
operation: "project-javascript-application",
limitation: analyzed.application_projection_failure.reason,
failure: analyzed.application_projection_failure.error,
limits: javaScriptAnalysisCoverageLimits(
analyzed.application_projection_failure.limits,
),
});
const packageValue = packagesByPath.get(file.path);
const packageValue = context.analysis.packages.find(
({ path }) => path === file.path,
);
if (packageValue !== undefined && packageValue.status !== "included")
addUnavailableStaticParseScope(context, {
file,
@@ -241,6 +173,9 @@ export const addJavaScriptArtifactFiles = (
operation: "parse-package-json",
limitation: packageValue.limitation,
});
const jsonValue = context.analysis.json_modules.find(
({ path }) => path === file.path,
);
if (jsonValue !== undefined && jsonValue.status !== "included")
addUnavailableStaticParseScope(context, {
file,
@@ -248,7 +183,9 @@ export const addJavaScriptArtifactFiles = (
operation: "parse-json-module",
limitation: jsonValue.limitation,
});
const sourceMap = sourceMapsByPath.get(file.path);
const sourceMap = context.analysis.source_maps.find(
({ path }) => path === file.path,
);
if (sourceMap !== undefined && sourceMap.status === "invalid")
addUnavailableStaticParseScope(context, {
file,
@@ -259,23 +196,6 @@ export const addJavaScriptArtifactFiles = (
}
};
const sourceFileRange = (
file: JavaScriptArtifactFile,
): JavaScriptSourceRange => {
if (!file.text.included)
throw new TypeError("Retained static facts require their source text");
let line = 1;
let lastLineStart = 0;
for (const match of file.text.value.matchAll(/\r\n|[\n\r\u2028\u2029]/gu)) {
line += 1;
lastLineStart = match.index + match[0].length;
}
return {
start: { line: 1, column: 0 },
end: { line, column: file.text.value.length - lastLineStart },
};
};
/** Project package metadata and its declared Electron roles. */
export const addJavaScriptPackageNodes = (
context: JavaScriptArtifactGraphContext,
@@ -350,9 +270,11 @@ const createFileTarget = (
context: JavaScriptArtifactGraphContext,
file: JavaScriptArtifactFile,
javascript: JavaScriptModuleArtifactAnalysis["files"][number]["javascript"],
json: JavaScriptModuleArtifactAnalysis["json_modules"][number] | undefined,
): ApplicationNode => {
const kind = artifactFileNodeKind(file.kind);
const json = context.analysis.json_modules.find(
({ path }) => path === file.path,
);
return context.accumulator.addNode({
kind,
identity: {
@@ -387,16 +309,6 @@ const createFileTarget = (
});
};
const indexFirstByPath = <Value extends { readonly path: string }>(
values: readonly Value[],
): ReadonlyMap<string, Value> => {
const index = new Map<string, Value>();
for (const value of values) {
if (!index.has(value.path)) index.set(value.path, value);
}
return index;
};
const createAsarEntry = (
context: JavaScriptArtifactGraphContext,
file: JavaScriptArtifactFile,
@@ -485,4 +397,3 @@ const containerProperties = (container: JavaScriptArtifactContainer) => ({
bytes: container.bytes,
inventory_artifact_id: container.inventory_artifact_id,
});
import { javaScriptAnalysisCoverageLimits } from "../../domain/javascript/javascriptAnalysisResourceControls.js";
@@ -234,8 +234,7 @@ const resolvePackageSpecifier = (
if (rawExports === undefined || rawExports === null) {
if (subpath === ".")
return resolveDirectory(input, directory, metadata, new Set());
// Preserve the trailing slash for a package directory request.
const candidate = confineCandidate(`${directory}/${subpath.slice(2)}`);
const candidate = confineCandidate(posix.join(directory, subpath.slice(2)));
return typeof candidate === "string"
? resolveCandidate(input, candidate, new Set())
: candidate;
@@ -11,22 +11,15 @@ import { createJavaScriptArtifactReader as createReader } from "../../artifacts/
import type { JavaScriptApplicationGraph } from "../../domain/javascript/javascriptApplicationGraph.js";
import type { JavaScriptSemanticGraph } from "../../domain/javascript/javascriptSemanticGraph.js";
import type { ElectronBoundarySummary } from "../../domain/javascript/javascriptApplicationAnalysis.js";
import { parseOwnedJavaScriptApplicationAnalysisSteps } from "../../domain/javascript/javascriptApplicationAnalysis.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySnapshot.js";
import type { ArtifactInventoryPartialObservation } from "../../domain/artifactPartialObservation.js";
import type { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
import { analyzeAndAdoptJavaScriptArtifactFiles } from "./JavaScriptArtifactAnalysis.js";
import { createJavaScriptSourceAnalysis } from "../../artifacts/javascript/JavaScriptSourceAnalysis.js";
import { JAVASCRIPT_ANALYSIS_RESOURCE_DEFAULTS } from "../../domain/javascript/javascriptAnalysisResourceControls.js";
import { createOwnedJavaScriptApplicationEvidenceCooperatively } from "./JavaScriptApplicationEvidence.js";
import { analyzeAndProjectJavaScriptArtifactFiles } from "./JavaScriptArtifactAnalysis.js";
import { readJavaScriptArtifactFiles } from "../../artifacts/javascript/JavaScriptArtifactFiles.js";
import { buildImmutableJavaScriptArtifactGraphSteps } from "./JavaScriptArtifactGraphBuilder.js";
import {
javascriptArtifactReconstructionInputSchema,
type JavaScriptArtifactReconstructionInput,
} from "./JavaScriptArtifactReconstructionInput.js";
import { scanCanonicalArtifactInventoryInScope } from "../../artifacts/inventory/scanCanonical.js";
import { scanCanonicalArtifactInventory } from "../../artifacts/inventory/scanCanonical.js";
import { summarizeElectronBoundaries } from "./ElectronBoundaryAnalysis.js";
import { createJavaScriptSemanticGraphProjection } from "./JavaScriptSemanticGraphBuilder.js";
import type { ProgressReporter } from "../ProgressReporter.js";
@@ -63,241 +56,118 @@ export interface JavaScriptArtifactReconstructionResult {
/** Reconstruct one local ASAR or extracted directory without executing code. */
export const reconstructJavaScriptArtifact = async (
rawInput: unknown,
scope: ArtifactResourceScope,
signal?: AbortSignal,
progress?: ProgressReporter,
): Promise<JavaScriptArtifactReconstructionResult> =>
scope.run(async () => {
let effectiveSignal = signal;
let effectiveProgress = progress;
const reportPhase = async (
phase: string,
message: string,
): Promise<void> => {
await effectiveProgress?.report({
phase,
completed: 0,
total: 1,
message,
});
await checkpointJavaScriptAnalysis(effectiveSignal);
};
const input = javascriptArtifactReconstructionInputSchema.parse(rawInput);
abortIfNeeded(signal);
const path = await resolveSelectedInput(input.input_path);
const format = await resolveFormat(path, input);
const snapshot = await scanCanonicalArtifactInventoryInScope(path, {
resourceScope: scope,
signal,
integrity: { mode: input.integrity_policy },
});
if (snapshot.manifest.root_format !== format)
throw new ArtifactReaderFailure(
"format",
`Artifact inventory classified ${path} as ${snapshot.manifest.root_format}, not ${format}`,
);
const reader = createReader(path, format);
const readerOwner = {
kind: "reader" as const,
reader,
resource: `JavaScript artifact reader for ${path}`,
};
let readerOpen = true;
let reconstructionOutcome:
| {
readonly kind: "completed";
readonly result: JavaScriptArtifactReconstructionResult;
}
| { readonly kind: "failed"; readonly cause: unknown };
try {
await reportPhase(
"read_javascript_artifacts",
"Reading inventoried JavaScript application sources",
);
const files = await readJavaScriptArtifactFiles(
reader,
snapshot,
scope,
signal,
);
// Release acquisition before analysis consumes these owned file facts.
const earlyCleanup = await scope.release(readerOwner);
readerOpen = false;
if (earlyCleanup.kind === "failed")
throw ArtifactReaderFailure.withCleanup(
earlyCleanup.cause,
ArtifactReaderFailure.cleanupObservation(
earlyCleanup.cause,
readerOwner.resource,
),
{ kind: "artifact-inventory", inventory: snapshot },
);
await reportPhase(
"parse_javascript_sources",
`Parsing and projecting ${String(files.files.length)} application source files`,
);
const semanticProjection = createJavaScriptSemanticGraphProjection();
const worker = createJavaScriptSourceAnalysis(
{
heapMb:
input.max_heap_mb ?? JAVASCRIPT_ANALYSIS_RESOURCE_DEFAULTS.heapMb,
timeoutMs:
input.analysis_timeout_ms ??
JAVASCRIPT_ANALYSIS_RESOURCE_DEFAULTS.timeoutMs,
},
files.files.filter(
(file) => file.kind === "javascript" && file.text.included,
).length,
);
let outcome;
let cleanupFailure: AnalysisError | undefined;
try {
outcome = await analyzeAndAdoptJavaScriptArtifactFiles(
files,
worker,
semanticProjection,
async (file, completed, total) => {
abortIfNeeded(signal);
await progress?.report({
phase: "parse_javascript_source",
completed: 0,
total: 1,
message: `Parsing and projecting ${file.path} (${String(completed + 1)}/${String(total)})`,
});
abortIfNeeded(signal);
},
signal,
);
} finally {
try {
const cleanup = await scope.release({
kind: "javascript-source-analysis",
analysis: worker,
resource: `JavaScript source analyzer for ${path}`,
});
if (cleanup.kind === "failed") throw cleanup.cause;
} catch (cause: unknown) {
if (!(cause instanceof AnalysisError)) throw cause;
cleanupFailure = cause;
}
}
const analysis = outcome.analysis;
const interruption = cleanupFailure ?? outcome.interruption;
if (interruption !== null && interruption !== undefined) {
effectiveSignal = undefined;
effectiveProgress = undefined;
}
await checkpointJavaScriptAnalysis(effectiveSignal);
abortIfNeeded(effectiveSignal);
await reportPhase(
"build_javascript_application_graph",
"Constructing application and Electron boundary relationships",
);
const applicationGraphSteps = buildImmutableJavaScriptArtifactGraphSteps(
snapshot,
files,
analysis,
);
await reportPhase(
"seal_javascript_application_graph",
"Sealing the validated application graph",
);
const graph = await completeJavaScriptAnalysisSteps(
applicationGraphSteps,
effectiveSignal,
);
await reportPhase(
"build_javascript_semantic_graph",
"Binding and validating static semantic relationships",
);
const semanticGraphSteps = semanticProjection.finishImmutableSteps(
snapshot.manifest.root_sha256,
graph,
);
await reportPhase(
"seal_javascript_semantic_graph",
"Validating and sealing the semantic graph",
);
const semanticGraph = await completeJavaScriptAnalysisSteps(
semanticGraphSteps,
effectiveSignal,
);
await checkpointJavaScriptAnalysis(effectiveSignal);
const completed = {
input_path: path,
format,
root_artifact_sha256: snapshot.manifest.root_sha256,
inventory_manifest_id: snapshot.manifest.manifest_id,
inventory_graph_sha256: snapshot.manifest.graph_sha256,
integrity_contradictions: snapshot.integrity_contradictions,
graph,
semantic_graph: semanticGraph,
electron_summary: summarizeElectronBoundaries(analysis),
statistics: {
relevant_files: files.files.length,
nested_asar_containers: files.containers.length,
text_bytes_read: files.text_bytes_read,
invalid_utf8_files: files.invalid_utf8_files,
parsed_javascript_files: analysis.files.filter(
({ javascript }) => javascript !== null,
).length,
visited_ast_nodes: analysis.visited_ast_nodes,
findings: analysis.findings,
modules: analysis.modules,
parse_failures: analysis.parse_failures,
},
limitations: analysis.limitations,
};
if (interruption !== null && interruption !== undefined) {
const { electron_summary: summary, ...application } = completed;
const partial = await completeJavaScriptAnalysisSteps(
parseOwnedJavaScriptApplicationAnalysisSteps({
...application,
summary,
limitations: completed.graph.limitations,
}),
);
const { max_heap_mb, analysis_timeout_ms, ...coreInput } = input;
const parameters = {
...coreInput,
...(max_heap_mb === undefined ? {} : { max_heap_mb }),
...(analysis_timeout_ms === undefined ? {} : { analysis_timeout_ms }),
};
const evidence =
await createOwnedJavaScriptApplicationEvidenceCooperatively(
parameters,
partial,
);
throw interruption.retainPartialObservation(evidence);
}
reconstructionOutcome = { kind: "completed", result: completed };
} catch (cause: unknown) {
reconstructionOutcome = { kind: "failed", cause };
}
if (readerOpen) {
const cleanupAttempt = await scope.release(readerOwner);
if (cleanupAttempt.kind === "failed") {
const cleanup = ArtifactReaderFailure.cleanupObservation(
cleanupAttempt.cause,
readerOwner.resource,
);
const partialObservation: ArtifactInventoryPartialObservation = {
kind: "artifact-inventory",
inventory: snapshot,
};
throw ArtifactReaderFailure.withCleanup(
reconstructionOutcome.kind === "failed"
? reconstructionOutcome.cause
: cleanupAttempt.cause,
cleanup,
partialObservation,
);
}
}
if (reconstructionOutcome.kind === "failed")
throw reconstructionOutcome.cause;
return reconstructionOutcome.result;
): Promise<JavaScriptArtifactReconstructionResult> => {
const reportPhase = async (phase: string, message: string): Promise<void> => {
await progress?.report({ phase, completed: 0, total: 1, message });
await checkpointJavaScriptAnalysis(signal);
};
const input = javascriptArtifactReconstructionInputSchema.parse(rawInput);
abortIfNeeded(signal);
const path = await resolveSelectedInput(input.input_path);
const format = await resolveFormat(path, input);
const snapshot = await scanCanonicalArtifactInventory(path, {
signal,
integrity: { mode: input.integrity_policy },
});
if (snapshot.manifest.root_format !== format)
throw new ArtifactReaderFailure(
"format",
`Artifact inventory classified ${path} as ${snapshot.manifest.root_format}, not ${format}`,
);
const reader = createReader(path, format);
try {
await reportPhase(
"read_javascript_artifacts",
"Reading inventoried JavaScript application sources",
);
const files = await readJavaScriptArtifactFiles(reader, snapshot, signal);
await reportPhase(
"parse_javascript_sources",
`Parsing and projecting ${String(files.files.length)} application source files`,
);
const semanticProjection = createJavaScriptSemanticGraphProjection();
const analysis = await analyzeAndProjectJavaScriptArtifactFiles(
files,
semanticProjection.projectFileSteps,
async (file, completed, total) => {
abortIfNeeded(signal);
await progress?.report({
phase: "parse_javascript_source",
completed: 0,
total: 1,
message: `Parsing and projecting ${file.path} (${String(completed + 1)}/${String(total)})`,
});
abortIfNeeded(signal);
},
signal,
);
await checkpointJavaScriptAnalysis(signal);
abortIfNeeded(signal);
await reportPhase(
"build_javascript_application_graph",
"Constructing application and Electron boundary relationships",
);
const applicationGraphSteps = buildImmutableJavaScriptArtifactGraphSteps(
snapshot,
files,
analysis,
);
await reportPhase(
"seal_javascript_application_graph",
"Sealing the validated application graph",
);
const graph = await completeJavaScriptAnalysisSteps(
applicationGraphSteps,
signal,
);
await reportPhase(
"build_javascript_semantic_graph",
"Binding and validating static semantic relationships",
);
const semanticGraphSteps = semanticProjection.finishImmutableSteps(
snapshot.manifest.root_sha256,
graph,
);
await reportPhase(
"seal_javascript_semantic_graph",
"Validating and sealing the semantic graph",
);
const semanticGraph = await completeJavaScriptAnalysisSteps(
semanticGraphSteps,
signal,
);
await checkpointJavaScriptAnalysis(signal);
return {
input_path: path,
format,
root_artifact_sha256: snapshot.manifest.root_sha256,
inventory_manifest_id: snapshot.manifest.manifest_id,
inventory_graph_sha256: snapshot.manifest.graph_sha256,
integrity_contradictions: snapshot.integrity_contradictions,
graph,
semantic_graph: semanticGraph,
electron_summary: summarizeElectronBoundaries(analysis),
statistics: {
relevant_files: files.files.length,
nested_asar_containers: files.containers.length,
text_bytes_read: files.text_bytes_read,
invalid_utf8_files: files.invalid_utf8_files,
parsed_javascript_files: analysis.files.filter(
({ javascript }) => javascript !== null,
).length,
visited_ast_nodes: analysis.visited_ast_nodes,
findings: analysis.findings,
modules: analysis.modules,
parse_failures: analysis.parse_failures,
},
limitations: analysis.limitations,
};
} finally {
await reader.close();
}
};
const OPERATION = "analyze_javascript_application";
@@ -1,13 +1,11 @@
import { z } from "zod";
import { artifactIntegrityPolicySchema } from "../../domain/artifactIntegrityPolicy.js";
import { javaScriptAnalysisResourceControlsSchema } from "../../domain/javascript/javascriptAnalysisResourceControls.js";
/** Local ASAR/directory reconstruction request. */
export const javascriptArtifactReconstructionInputSchema = z.strictObject({
input_path: z.string().min(1),
format: z.enum(["auto", "asar", "directory"]).default("auto"),
integrity_policy: artifactIntegrityPolicySchema,
...javaScriptAnalysisResourceControlsSchema.shape,
});
/** Parsed local reconstruction request. */
@@ -8,7 +8,7 @@ import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { javascriptApplicationAnalysisResultSchema } from "../../domain/javascript/javascriptApplicationAnalysis.js";
import { staticPath } from "../../domain/javascript/javascriptStaticAnalysisHelpers.js";
import { analyzeJavaScriptApplication } from "../../../tests/support/javascriptApplicationScope.js";
import { analyzeJavaScriptApplication } from "./JavaScriptApplicationService.js";
const urlCases = [
["./preload%20name.cjs", "preload name.cjs", "main.mjs"],
@@ -7,7 +7,7 @@ import { promisify } from "node:util";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
import { resolveArtifactPathByContext } from "./JavaScriptArtifactPathResolution.js";
import { analyzeJavaScriptApplication } from "../../../tests/support/javascriptApplicationScope.js";
import { analyzeJavaScriptApplication } from "./JavaScriptApplicationService.js";
import { javascriptApplicationAnalysisResultSchema } from "../../domain/javascript/javascriptApplicationAnalysis.js";
const filesFor = (paths: readonly string[]) =>
@@ -5,7 +5,7 @@ import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { javascriptApplicationAnalysisResultSchema } from "../../domain/javascript/javascriptApplicationAnalysis.js";
import { analyzeJavaScriptApplication } from "../../../tests/support/javascriptApplicationScope.js";
import { analyzeJavaScriptApplication } from "./JavaScriptApplicationService.js";
it("classifies overloaded open calls from lexical receiver facts", async () => {
const inputPath = await createTestTempDirectory(
@@ -1,6 +1,5 @@
import {
createJavaScriptSemanticGraph,
createJavaScriptSemanticGraphUnknown,
sealTransferredJavaScriptSemanticGraphSteps,
type JavaScriptSemanticGraph,
} from "../../domain/javascript/javascriptSemanticGraph.js";
@@ -11,7 +10,6 @@ import type {
import {
JAVASCRIPT_SEMANTIC_RELATION_FAMILIES,
JAVASCRIPT_SEMANTIC_RELATION_FAMILY,
JAVASCRIPT_SEMANTIC_RELATIONS,
} from "../../domain/javascript/javascriptSemanticGraphSchemas.js";
import type {
JavaScriptSemanticCallArgument,
@@ -35,13 +33,6 @@ import { projectSemanticResources } from "./JavaScriptSemanticGraphResourceProje
import { projectSemanticObjects } from "./JavaScriptSemanticGraphObjectProjection.js";
import { projectSemanticValues } from "./JavaScriptSemanticGraphValueProjection.js";
import { inferredSemanticEvidenceAt } from "./JavaScriptSemanticGraphEvidence.js";
import { observedSemanticEvidence } from "./JavaScriptSemanticGraphEvidence.js";
import {
partialApplicationCoverage,
type ApplicationCoverage,
} from "../../domain/javascript/javascriptApplicationEvidenceSchemas.js";
import type { JsonValue } from "../../domain/jsonValue.js";
import { javaScriptAnalysisCoverageLimits } from "../../domain/javascript/javascriptAnalysisResourceControls.js";
import { projectSemanticFunctionFingerprints } from "./JavaScriptSemanticGraphFingerprintProjection.js";
import {
projectSemanticClosureCaptures,
@@ -64,7 +55,6 @@ import {
bindSemanticGraphApplicationNodes,
type SemanticGraphProjectionState as BuilderState,
} from "./JavaScriptSemanticGraphConstruction.js";
import type { JavaScriptSemanticFileProjection } from "../../domain/javascript/javascriptSemanticFileProjection.js";
interface BuilderInput {
readonly rootArtifactSha256: string;
@@ -136,19 +126,6 @@ export const buildJavaScriptSemanticGraph = ({
/** File-local semantic projection that does not retain consumed source IR. */
export interface JavaScriptSemanticGraphProjection {
/** Node capacity offered to the next independently analyzed source file. */
readonly remainingFileNodeBudget: () => number;
/** Adopt decoded file-local facts; final validation and proof remain in this realm. */
readonly adoptFileProjection: (
projection: JavaScriptSemanticFileProjection,
) => void;
/** Preserve source-bound unknowns for an execution or result-retention failure. */
readonly recordUnavailableFile: (
file: JavaScriptArtifactFile,
reason: string,
limits: Readonly<Record<string, JsonValue>> | null,
unknownReason: "resource-limit" | "incomplete-module",
) => void;
readonly projectFile: (
file: JavaScriptArtifactFile,
ir: JavaScriptSemanticIr,
@@ -174,12 +151,6 @@ export const createJavaScriptSemanticGraphProjection =
const state = emptyState();
const fingerprints: JavaScriptSemanticFingerprint[] = [];
let truncatedFiles = 0;
let unavailableFiles = 0;
let resourceTruncatedFiles = 0;
const executionLimits = new Map<
string,
ApplicationCoverage["limits"][number]
>();
const projectSourceSteps = function* (
file: JavaScriptArtifactFile,
ir: JavaScriptSemanticIr,
@@ -236,15 +207,12 @@ export const createJavaScriptSemanticGraphProjection =
fingerprints: [...fingerprints],
unknowns,
coverage: {
status:
truncatedFiles > 0 || unavailableFiles > 0 ? "partial" : "unknown",
truncated: truncatedFiles > 0 || resourceTruncatedFiles > 0,
omitted_nodes: truncatedFiles > 0 || unavailableFiles > 0 ? null : 0,
omitted_relations:
truncatedFiles > 0 || unavailableFiles > 0 ? null : 0,
limits: [
...executionLimits.values(),
...(truncatedFiles > 0
status: truncatedFiles > 0 ? "partial" : "unknown",
truncated: truncatedFiles > 0,
omitted_nodes: truncatedFiles > 0 ? null : 0,
omitted_relations: truncatedFiles > 0 ? null : 0,
limits:
truncatedFiles > 0
? [
{
name: "semantic_graph_node_ceiling",
@@ -252,14 +220,12 @@ export const createJavaScriptSemanticGraphProjection =
unit: "items" as const,
},
]
: []),
],
: [],
families: JAVASCRIPT_SEMANTIC_RELATION_FAMILIES.map((family) => ({
family,
status: semanticFamilyStatus(family),
retained_relations: retainedByFamily.get(family) ?? 0,
omitted_relations:
truncatedFiles > 0 || unavailableFiles > 0 ? null : 0,
omitted_relations: truncatedFiles > 0 ? null : 0,
unknown_ids: unknownIdsByFamily.get(family) ?? [],
})),
},
@@ -286,87 +252,6 @@ export const createJavaScriptSemanticGraphProjection =
return graph;
};
return {
remainingFileNodeBudget: () =>
Math.min(
SEMANTIC_GRAPH_FILE_NODE_CEILING,
Math.max(0, SEMANTIC_GRAPH_NODE_CEILING - state.nodes.size),
),
adoptFileProjection: (projection) => {
const newNodes = projection.nodes.filter(
({ node_id }) => !state.nodes.has(node_id),
);
if (
newNodes.length >
Math.min(
SEMANTIC_GRAPH_FILE_NODE_CEILING,
SEMANTIC_GRAPH_NODE_CEILING - state.nodes.size,
)
)
throw new RangeError(
"Transferred semantic nodes exceed the offered tree capacity",
);
for (const context of projection.evidenceContexts)
state.evidenceContexts.adopt(context);
for (const node of newNodes) state.nodes.set(node.node_id, node);
for (const relation of projection.relations)
state.relations.set(relation.relation_id, relation);
for (const unknown of projection.unknowns)
state.unknowns.set(unknown.unknown_id, unknown);
for (const root of projection.roots) state.roots.add(root);
fingerprints.push(...projection.fingerprints);
if (projection.truncated) truncatedFiles += 1;
},
recordUnavailableFile: (file, reason, limits, unknownReason) => {
const retainedLimits = javaScriptAnalysisCoverageLimits(limits);
for (const limit of retainedLimits) {
executionLimits.set(
JSON.stringify([limit.name, limit.value, limit.unit]),
limit,
);
}
state.fileNodeBudget = Math.min(
SEMANTIC_GRAPH_FILE_NODE_CEILING,
Math.max(0, SEMANTIC_GRAPH_NODE_CEILING - state.nodes.size),
);
const module = retainNode(state, file, {
kind: "module",
roleKey: "module",
location: null,
label: file.path,
functionNodeId: null,
});
state.fileNodeBudget = null;
if (module !== null) state.roots.add(module.node_id);
const evidence = {
...observedSemanticEvidence(file, null),
authority: "unknown" as const,
state: "unknown" as const,
confidence: "unknown" as const,
coverage: partialApplicationCoverage(retainedLimits, null),
limitations: [reason],
};
for (const family of JAVASCRIPT_SEMANTIC_RELATION_FAMILIES) {
const unknown = createJavaScriptSemanticGraphUnknown(
{
node_id: module?.node_id ?? null,
family,
relation_kinds: JAVASCRIPT_SEMANTIC_RELATIONS.filter(
(relation) =>
JAVASCRIPT_SEMANTIC_RELATION_FAMILY[relation] === family,
),
reason: unknownReason,
detail: reason,
candidate_node_ids: [],
evidence,
},
state.evidenceContexts,
);
state.unknowns.set(unknown.unknown_id, unknown);
}
unavailableFiles += 1;
if (unknownReason === "resource-limit" && retainedLimits.length > 0)
resourceTruncatedFiles += 1;
},
projectFile: (file, ir) => {
const steps = projectSourceSteps(file, ir);
while (steps.next().done !== true);
@@ -387,35 +272,6 @@ export const createJavaScriptSemanticGraphProjection =
};
};
/** Project one source with the parent's remaining node capacity, retaining no full IR. */
export function* projectJavaScriptSemanticFileSteps(
file: JavaScriptArtifactFile,
ir: JavaScriptSemanticIr,
nodeBudget: number,
): Generator<void, JavaScriptSemanticFileProjection> {
if (
!Number.isSafeInteger(nodeBudget) ||
nodeBudget < 0 ||
nodeBudget > SEMANTIC_GRAPH_FILE_NODE_CEILING
)
throw new RangeError(
"File semantic projection requires a valid offered node capacity",
);
const state = emptyState();
state.fileNodeBudget = nodeBudget;
state.fileNodesDropped = false;
const fingerprints = yield* projectFileSteps(file, ir, state);
return {
roots: [...state.roots],
evidenceContexts: state.evidenceContexts.contexts,
nodes: [...state.nodes.values()],
relations: [...state.relations.values()],
unknowns: [...state.unknowns.values()],
fingerprints,
truncated: Boolean(state.fileNodesDropped),
};
}
function* projectFileSteps(
file: JavaScriptArtifactFile,
ir: JavaScriptSemanticIr,
@@ -7,7 +7,6 @@ import {
import { ghidraFunctionDossier } from "../../domain/ghidraValues.fixture.js";
import { functionDossierSchema } from "../../domain/hopperValues.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import { nativeValueTraceSchema } from "../../domain/native/nativeValueTrace.js";
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
import { ok, err } from "../../domain/result.js";
@@ -103,132 +102,6 @@ const analysis: AnalysisOperationPort = {
);
},
};
describe("native value parameter-use node membership", () => {
it("retains only parameter uses whose parameter nodes fit the node budget", async () => {
const operationCount = 3_000;
const parameterUseCount = 12_000;
const base = functionDossierSchema.parse(ghidraFunctionDossier());
const procedureAddress = base.procedure.address;
const largeFlow = {
available: true as const,
provenance: "ghidra-high-pcode" as const,
operations: Array.from({ length: operationCount }, (_, index) => ({
...node(`operation-${String(index)}`, procedureAddress, "MULTIEQUAL"),
inputs: [scalar, scalar, scalar, scalar],
})),
def_use: [],
effects: [],
parameters: [{ ordinal: 0, name: "value", data_type: "/int" }],
parameter_uses: Array.from({ length: parameterUseCount }, (_, index) => ({
ordinal: 0,
use: `operation-${String(index % operationCount)}`,
input_index: Math.floor(index / operationCount),
})),
truncated: false,
omitted_operations_lower_bound: 0,
known_omitted_inputs: 0,
known_omitted_edges: 0,
limitations: [],
};
const largeDossier = {
...base,
native_value_flow: largeFlow,
};
const largeAnalysis: AnalysisOperationPort = {
execute: async () =>
ok(createAnalysisExecution(largeDossier, provider, { subject })),
};
const includedParameter = await traceNativeValues(largeAnalysis, {
procedure: procedureAddress,
max_nodes: 20_000,
max_edges: 40_000,
offset: operationCount,
limit: 1,
});
if (!includedParameter.ok) throw includedParameter.error;
const includedResult = nativeValueTraceSchema.parse(
includedParameter.value,
);
expect(includedResult).toMatchObject({
total_nodes: operationCount + 1,
total_edges: parameterUseCount,
nodes: [
expect.objectContaining({
id: `${procedureAddress}/parameter:0`,
kind: "parameter",
}),
],
truncated: true,
});
expect(includedResult.edges).toHaveLength(parameterUseCount);
const omittedParameter = await traceNativeValues(largeAnalysis, {
procedure: procedureAddress,
max_nodes: operationCount,
max_edges: 40_000,
offset: operationCount - 1,
limit: 1,
});
if (!omittedParameter.ok) throw omittedParameter.error;
const omittedResult = nativeValueTraceSchema.parse(omittedParameter.value);
expect(omittedResult).toMatchObject({
total_nodes: operationCount,
total_edges: 0,
nodes: [expect.objectContaining({ kind: "operation" })],
edges: [],
truncated: true,
});
});
it("preserves operation IDs that collide with generated parameter IDs", async () => {
const base = functionDossierSchema.parse(ghidraFunctionDossier());
const address = base.procedure.address;
const execution = createAnalysisExecution(
{
...base,
native_value_flow: {
available: true,
provenance: "ghidra-high-pcode",
operations: [
node("parameter:0", address, "COPY"),
node("use", address, "COPY"),
],
def_use: [],
effects: [],
parameters: [{ ordinal: 0, name: "value", data_type: "/int" }],
parameter_uses: [{ ordinal: 0, use: "use", input_index: 1 }],
truncated: false,
omitted_operations_lower_bound: 0,
known_omitted_inputs: 0,
known_omitted_edges: 0,
limitations: [],
},
},
provider,
{ subject },
);
const result = await traceNativeValues(
{ execute: async () => ok(execution) },
{ procedure: address, max_nodes: 2 },
);
if (!result.ok) throw result.error;
const parsedResult = nativeValueTraceSchema.parse(result.value);
expect(parsedResult).toMatchObject({
total_nodes: 2,
total_edges: 1,
edges: [
{
source: `${address}/parameter:0`,
target: `${address}/use`,
kind: "parameter-use",
},
],
});
});
});
describe("bounded native value dependency composition", () => {
it("reports work truncation and stable pagination without traversing ambiguous calls", async () => {
const bounded = await traceNativeValues(analysis, {
+2 -6
View File
@@ -21,7 +21,6 @@ export const traceNativeValues = async (
): EnhancedResult => {
const input = nativeValueTraceInputSchema.parse(parameters);
const nodes: typeof nativeValueTraceSchema._output.nodes = [];
const nodeIds = new Set<string>();
const edges: typeof nativeValueTraceSchema._output.edges = [];
const procedures: typeof nativeValueTraceSchema._output.procedures = [];
const unknowns: typeof nativeValueTraceSchema._output.unknowns = [];
@@ -155,28 +154,25 @@ export const traceNativeValues = async (
bytes += size;
ids.add(operation.id);
nodes.push(node);
nodeIds.add(node.id);
}
for (const parameter of flow.parameters) {
if (nodes.length >= input.max_nodes) {
truncated = true;
break;
}
const id = `${address}/parameter:${parameter.ordinal}`;
nodes.push({
id,
id: `${address}/parameter:${parameter.ordinal}`,
procedure: address,
evidence_id: evidenceId,
kind: "parameter",
operation: null,
parameter,
});
nodeIds.add(id);
}
for (const use of flow.parameter_uses) {
if (
!ids.has(use.use) ||
!nodeIds.has(`${address}/parameter:${use.ordinal}`)
!nodes.some((node) => node.id === `${address}/parameter:${use.ordinal}`)
)
continue;
if (edges.length >= input.max_edges) {
+1 -25
View File
@@ -33,12 +33,10 @@ import type { JsonValue } from "../domain/jsonValue.js";
import { interfaceBuilderLimitsSchema } from "../domain/apple/interfaceBuilderGraph.js";
import { err, ok, type Result } from "../domain/result.js";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
import { ArtifactResourceScope } from "./ArtifactResourceScope.js";
import { artifactCapabilities } from "./ArtifactProviderMetadata.js";
import { ARTIFACT_GRAPH_PROVIDER } from "../application/InvestigationProviders.js";
import { createEvidence } from "../domain/evidence.js";
import { createArtifactInspection } from "../domain/artifactInspection.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
/** Read-only inventory and exclusively owned extraction provider. */
export class ArtifactProvider implements AnalysisProvider {
@@ -69,8 +67,6 @@ export class ArtifactProvider implements AnalysisProvider {
}
class ArtifactClient implements AnalysisClient {
readonly #resourceScope = new ArtifactResourceScope();
constructor(
private readonly target: BinaryTarget,
private readonly environment: Readonly<NodeJS.ProcessEnv>,
@@ -188,7 +184,6 @@ class ArtifactClient implements AnalysisClient {
outputRoot: parsed.output_root,
environment: this.environment,
integrityPolicy: parsed.integrity_policy,
resourceScope: this.#resourceScope,
},
options?.signal,
);
@@ -225,25 +220,7 @@ class ArtifactClient implements AnalysisClient {
}
close(): Promise<Result<null, AnalysisError>> {
return this.#resourceScope.close().then(
() => ok(null),
(cause: unknown) => {
const failure =
cause instanceof ArtifactReaderFailure ? cause : undefined;
return err(
new ProviderCleanupError(
ARTIFACT_GRAPH_PROVIDER.id,
failure?.cleanup?.resources ?? ["artifact resources"],
{
reason:
failure?.cleanup?.reason ??
(cause instanceof Error ? cause.message : String(cause)),
},
{ cause, operation: "close_binary" },
),
);
},
);
return Promise.resolve(ok(null));
}
/** The active target's kind is outside this operation's supported targets. */
@@ -376,7 +353,6 @@ class ArtifactClient implements AnalysisClient {
options?: ExecutionOptions,
) {
return inventoryArtifact(this.target.sourcePath ?? this.target.path, {
resourceScope: this.#resourceScope,
environment: this.environment,
...(options?.signal === undefined ? {} : { signal: options.signal }),
integrity: { mode: parsed.integrity_policy },
-31
View File
@@ -31,37 +31,6 @@ export interface ArtifactEntry {
};
}
/** Snapshot mutable entry metadata before the producer later validates open(). */
export const copyArtifactEntry = (entry: ArtifactEntry): ArtifactEntry => ({
...entry,
limitations: [...entry.limitations],
...(entry.sourceIdentity === undefined
? {}
: { sourceIdentity: { ...entry.sourceIdentity } }),
});
/** Compare every portable and adapter-owned fact supplied with an entry. */
export const sameArtifactEntry = (
entry: ArtifactEntry,
produced: ArtifactEntry,
): boolean =>
entry.path === produced.path &&
entry.kind === produced.kind &&
entry.declaredSize === produced.declaredSize &&
entry.compressedSize === produced.compressedSize &&
entry.executable === produced.executable &&
entry.encrypted === produced.encrypted &&
entry.byteOffset === produced.byteOffset &&
entry.declaredSha256 === produced.declaredSha256 &&
entry.unpacked === produced.unpacked &&
entry.adapterKey === produced.adapterKey &&
entry.limitations.length === produced.limitations.length &&
entry.limitations.every(
(limitation, index) => limitation === produced.limitations[index],
) &&
entry.sourceIdentity?.device === produced.sourceIdentity?.device &&
entry.sourceIdentity?.inode === produced.sourceIdentity?.inode;
/** Read-only adapter over one directory, archive, or virtual container. */
export interface ArtifactReader {
readonly format: "directory" | ZipPackageFormat | "asar" | "file";
-114
View File
@@ -1,114 +0,0 @@
import { expect, it } from "vitest";
import { err } from "../domain/result.js";
import { AnalysisOutputError } from "../domain/analysisErrorCore.js";
import type { ArtifactReader } from "./ArtifactReader.js";
import { ArtifactResourceScope } from "./ArtifactResourceScope.js";
const deferred = <T>() => {
let resolve: (value: T) => void = () => {};
const promise = new Promise<T>((resolvePromise) => {
resolve = resolvePromise;
});
return { promise, resolve };
};
it("waits for admitted operations and shares concurrent close", async () => {
const scope = new ArtifactResourceScope();
const started = deferred<void>();
const finish = deferred<void>();
const operation = scope.run(async () => {
started.resolve();
await finish.promise;
});
await started.promise;
const close = scope.close();
expect(scope.close()).toBe(close);
await expect(scope.run(async () => undefined)).rejects.toMatchObject({
reason: "unavailable",
message: "Artifact resource scope is closed",
});
let closed = false;
void close.then(() => {
closed = true;
});
await Promise.resolve();
expect(closed).toBe(false);
finish.resolve();
await operation;
await close;
expect(closed).toBe(true);
});
it("retains the same failed reader owner and retries before admitting work", async () => {
const scope = new ArtifactResourceScope();
let closeAttempts = 0;
const reader = {
async close() {
closeAttempts += 1;
if (closeAttempts < 4) throw new Error(`close attempt ${closeAttempts}`);
},
} as unknown as ArtifactReader;
const owner = { kind: "reader" as const, resource: "fixture reader", reader };
expect(await scope.release(owner)).toMatchObject({ kind: "failed" });
expect(closeAttempts).toBe(1);
await expect(scope.run(async () => "must not run")).rejects.toMatchObject({
reason: "unavailable",
message: "Artifact cleanup remains incomplete: fixture reader",
});
expect(closeAttempts).toBe(2);
await expect(scope.close()).rejects.toMatchObject({
reason: "unavailable",
});
expect(closeAttempts).toBe(3);
await scope.close();
expect(closeAttempts).toBe(4);
});
it("retains a failed source analyzer until shutdown can verify its release", async () => {
const scope = new ArtifactResourceScope();
let releaseAllowed = false;
const failure = new AnalysisOutputError(
"analyze_javascript_application",
"Owned worker is still running",
);
const owner = {
kind: "javascript-source-analysis" as const,
resource: "fixture source analyzer",
analysis: {
async analyze() {
return err({
error: failure,
javascript: null,
module: null,
projection: null,
});
},
async close() {
if (!releaseAllowed) throw failure;
},
},
};
expect(await scope.release(owner)).toEqual({
kind: "failed",
cause: failure,
});
let admitted = false;
await expect(
scope.run(async () => {
admitted = true;
}),
).rejects.toMatchObject({
cleanup: { resources: ["fixture source analyzer"] },
});
expect(admitted).toBe(false);
await expect(scope.close()).rejects.toMatchObject({
cleanup: { resources: ["fixture source analyzer"] },
});
releaseAllowed = true;
await scope.close();
});
-156
View File
@@ -1,156 +0,0 @@
import type { JavaScriptSourceAnalysisPort } from "../domain/javascript/javascriptSourceAnalysis.js";
import type { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import type { OwnedDirectoryHandle } from "../filesystem/OwnedDirectoryHandle.js";
import type { ArtifactReader } from "./ArtifactReader.js";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
import type { SafeOutputTree } from "./SafeOutputTree.js";
/** One artifact resource and its format-specific cleanup owner. */
export type ArtifactResourceOwner =
| {
readonly kind: "javascript-source-analysis";
readonly resource: string;
readonly analysis: JavaScriptSourceAnalysisPort;
}
| {
readonly kind: "directory-handle";
readonly resource: string;
readonly handle: OwnedDirectoryHandle;
}
| {
readonly kind: "reader";
readonly resource: string;
readonly reader: ArtifactReader;
}
| {
readonly kind: "file-handle";
readonly resource: string;
readonly handle: OwnedFileHandle;
}
| {
readonly kind: "output-tree";
readonly resource: string;
readonly tree: SafeOutputTree;
};
export type ArtifactCleanupAttempt =
| { readonly kind: "released" }
| { readonly kind: "failed"; readonly cause: unknown };
/** Caller-owned scope that retains failed artifact cleanup for a later close. */
export class ArtifactResourceScope {
readonly #pending = new Set<ArtifactResourceOwner>();
readonly #active = new Set<Promise<unknown>>();
#draining: Promise<void> | undefined;
#closed = false;
/** Admit a resource operation while the scope remains open. */
async run<T>(operation: () => Promise<T>): Promise<T> {
while (true) {
if (this.#closed)
throw new ArtifactReaderFailure(
"unavailable",
"Artifact resource scope is closed",
);
if (this.#draining !== undefined) await this.#draining;
if (this.#closed)
throw new ArtifactReaderFailure(
"unavailable",
"Artifact resource scope is closed",
);
if (this.#pending.size > 0) {
await this.#retryCleanup();
continue;
}
const running = Promise.resolve().then(operation);
this.#active.add(running);
try {
return await running;
} finally {
this.#active.delete(running);
}
}
}
/** Attempt cleanup now and retain the same owner if it fails. */
async release(owner: ArtifactResourceOwner): Promise<ArtifactCleanupAttempt> {
try {
await cleanup(owner);
this.#pending.delete(owner);
return { kind: "released" };
} catch (cause: unknown) {
this.#pending.add(owner);
return { kind: "failed", cause };
}
}
/** Retry retained owners without closing resource admission. */
#retryCleanup(): Promise<void> {
if (this.#draining !== undefined) return this.#draining;
this.#draining = this.#drainAndRetry().finally(() => {
this.#draining = undefined;
});
return this.#draining;
}
/** Stop admission, wait for active operations, and retry every retained owner. */
close(): Promise<void> {
this.#closed = true;
return this.#retryCleanup();
}
async #drainAndRetry(): Promise<void> {
while (this.#active.size > 0) await Promise.allSettled(this.#active);
const failures: {
readonly owner: ArtifactResourceOwner;
readonly cause: unknown;
}[] = [];
for (const owner of this.#pending) {
try {
await cleanup(owner);
this.#pending.delete(owner);
} catch (cause: unknown) {
failures.push({ owner, cause });
}
}
if (failures.length === 0) return;
const observations = failures.map(({ owner, cause }) =>
ArtifactReaderFailure.cleanupObservation(cause, owner.resource),
);
const resources = [
...new Set(observations.flatMap(({ resources }) => resources)),
];
throw new ArtifactReaderFailure(
"unavailable",
`Artifact cleanup remains incomplete: ${resources.join(", ")}`,
{
cause: new AggregateError(
failures.map(({ cause }) => cause),
"One or more artifact resources remain owned",
),
cleanup: {
reason: observations.map(({ reason }) => reason).join("; "),
resources,
},
},
);
}
}
const cleanup = async (owner: ArtifactResourceOwner): Promise<void> => {
switch (owner.kind) {
case "javascript-source-analysis":
await owner.analysis.close();
return;
case "reader":
await owner.reader.close();
return;
case "file-handle":
case "directory-handle":
await owner.handle.close();
return;
case "output-tree":
await owner.tree.rollback();
}
};
+49 -22
View File
@@ -23,15 +23,11 @@ import { listPackage, statFile, uncache } from "@electron/asar";
import {
ArtifactReaderFailure,
copyArtifactEntry,
sameArtifactEntry,
type ArtifactEntry,
type ArtifactReader,
} from "./ArtifactReader.js";
import { closeAsarHandle, readValidatedAsarEntry } from "./AsarEntryStream.js";
import { admitAsarHeader } from "./AsarHeader.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import { readFileHandleChunks } from "../filesystem/readFileHandleChunks.js";
/**
* Official Electron ASAR adapter with range-streamed member reads.
@@ -45,12 +41,10 @@ export class AsarArtifactReader implements ArtifactReader {
#archiveSize: number | undefined;
#headerSize: number | undefined;
readonly #entries = new Map<string, AsarEntryState>();
readonly #unpackedHandles = new Map<
readonly #unpackedHandles = new Map<UnpackedFileHandle, string>();
readonly #unpackedHandleClosePromises = new Map<
UnpackedFileHandle,
{
readonly path: string;
readonly owner: OwnedFileHandle<UnpackedFileHandle>;
}
Promise<void>
>();
#snapshot: { readonly path: string; readonly sha256: string } | undefined;
#snapshotRoot: string | undefined;
@@ -303,7 +297,7 @@ export class AsarArtifactReader implements ArtifactReader {
async close(): Promise<void> {
let cleanupFailure: ArtifactReaderFailure | undefined;
for (const [handle, { path }] of this.#unpackedHandles) {
for (const [handle, path] of this.#unpackedHandles) {
try {
await this.#closeUnpackedHandle(handle);
} catch (cause: unknown) {
@@ -387,10 +381,7 @@ export class AsarArtifactReader implements ArtifactReader {
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
);
const openedHandle = handle;
this.#unpackedHandles.set(openedHandle, {
path: canonical,
owner: new OwnedFileHandle(openedHandle),
});
this.#unpackedHandles.set(openedHandle, canonical);
const openedMetadata = await openedHandle.stat();
if (
!openedMetadata.isFile() ||
@@ -410,8 +401,9 @@ export class AsarArtifactReader implements ArtifactReader {
);
}
abortIfNeeded(signal);
const source = readFileHandleChunks(openedHandle, {
const source = openedHandle.createReadStream({
start: 0,
autoClose: false,
});
source.once("close", () => {
void this.#closeUnpackedHandle(openedHandle).catch(() => undefined);
@@ -433,7 +425,7 @@ export class AsarArtifactReader implements ArtifactReader {
failure,
ArtifactReaderFailure.cleanupObservation(
cleanupCause,
this.#unpackedHandles.get(handle)?.path ?? entry.path,
this.#unpackedHandles.get(handle) ?? entry.path,
),
);
}
@@ -443,10 +435,17 @@ export class AsarArtifactReader implements ArtifactReader {
}
async #closeUnpackedHandle(handle: UnpackedFileHandle): Promise<void> {
const owned = this.#unpackedHandles.get(handle);
if (owned === undefined) return;
await owned.owner.close();
this.#unpackedHandles.delete(handle);
if (!this.#unpackedHandles.has(handle)) return;
const pending = this.#unpackedHandleClosePromises.get(handle);
if (pending !== undefined) return pending;
const closing = Promise.resolve()
.then(() => handle.close())
.then(() => {
this.#unpackedHandles.delete(handle);
})
.finally(() => this.#unpackedHandleClosePromises.delete(handle));
this.#unpackedHandleClosePromises.set(handle, closing);
return closing;
}
#resetArchiveState(): void {
@@ -461,10 +460,9 @@ type AsarEntryState = {
readonly entry: ArtifactEntry;
};
type UnpackedFileHandle = {
readonly fd: number;
stat(): Promise<Stats>;
close(): Promise<void>;
read: FileHandle["read"];
createReadStream: FileHandle["createReadStream"];
};
type OpenAsarUnpackedFile = (
path: string,
@@ -492,6 +490,35 @@ const asarUnpackedEntryFailure = (
return asarFailure(archivePath, `read ${entry.path}`, cause);
};
const copyArtifactEntry = (entry: ArtifactEntry): ArtifactEntry => ({
...entry,
limitations: [...entry.limitations],
...(entry.sourceIdentity === undefined
? {}
: { sourceIdentity: { ...entry.sourceIdentity } }),
});
const sameArtifactEntry = (
entry: ArtifactEntry,
produced: ArtifactEntry,
): boolean =>
entry.path === produced.path &&
entry.kind === produced.kind &&
entry.declaredSize === produced.declaredSize &&
entry.compressedSize === produced.compressedSize &&
entry.executable === produced.executable &&
entry.encrypted === produced.encrypted &&
entry.byteOffset === produced.byteOffset &&
entry.declaredSha256 === produced.declaredSha256 &&
entry.unpacked === produced.unpacked &&
entry.adapterKey === produced.adapterKey &&
entry.limitations.length === produced.limitations.length &&
entry.limitations.every(
(limitation, index) => limitation === produced.limitations[index],
) &&
entry.sourceIdentity?.device === produced.sourceIdentity?.device &&
entry.sourceIdentity?.inode === produced.sourceIdentity?.inode;
const isAsarFileMetadata = (
metadata: ReturnType<typeof statFile>,
): metadata is AsarFileMetadata =>
+69 -238
View File
@@ -1,33 +1,23 @@
import { constants, type Stats } from "node:fs";
import {
lstat,
open,
opendir,
realpath,
type FileHandle,
} from "node:fs/promises";
import { constants } from "node:fs";
import { lstat, open, opendir, realpath } from "node:fs/promises";
import { isAbsolute, join, relative, sep } from "node:path";
import { Readable } from "node:stream";
import type { Readable } from "node:stream";
import {
ArtifactReaderFailure,
type ArtifactEntry,
type ArtifactReader,
} from "./ArtifactReader.js";
import { OwnedDirectoryHandle } from "../filesystem/OwnedDirectoryHandle.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import { readFileHandleChunks } from "../filesystem/readFileHandleChunks.js";
/** Non-symlink-following directory reader. */
export class DirectoryArtifactReader implements ArtifactReader {
readonly format = "directory" as const;
#rootPromise: Promise<string> | undefined;
readonly #rootPromise: Promise<string>;
readonly #rootPath: string;
readonly #directories = new Set<OwnedDirectoryHandle>();
readonly #files = new Map<OwnedFileHandle, string>();
constructor(root: string) {
this.#rootPath = root;
this.#rootPromise = realpath(root);
}
/** Enumerate entries, optionally restricting descent while retaining directories. */
@@ -35,7 +25,9 @@ export class DirectoryArtifactReader implements ArtifactReader {
signal?: AbortSignal,
descendInto?: (path: string) => boolean,
): AsyncIterable<ArtifactEntry> {
const root = await this.#resolveRoot();
const root = await this.#rootPromise.catch((cause: unknown) => {
throw directoryIoFailure("resolve artifact root", this.#rootPath, cause);
});
const pending = [root];
while (pending.length > 0) {
abortIfNeeded(signal);
@@ -44,100 +36,62 @@ export class DirectoryArtifactReader implements ArtifactReader {
await withDirectoryIoContext("inspect directory", directory, () =>
assertContainedDirectory(root, directory),
);
for await (const entry of this.#readDirectory(
directory,
pending,
signal,
descendInto,
))
yield entry;
const handle = await opendir(directory).catch((cause: unknown) => {
throw directoryIoFailure("open directory", directory, cause);
});
const directories: string[] = [];
try {
for await (const child of handle) {
abortIfNeeded(signal);
const absolute = join(directory, child.name);
const metadata = await lstat(absolute).catch((cause: unknown) => {
throw directoryIoFailure("inspect entry", absolute, cause);
});
const path = relative(root, absolute).split(sep).join("/");
const kind = metadata.isSymbolicLink()
? "symlink"
: metadata.isDirectory()
? "directory"
: metadata.isFile()
? "file"
: undefined;
if (kind === undefined) continue;
yield {
path,
kind,
declaredSize: kind === "file" ? metadata.size : null,
compressedSize: null,
executable: (metadata.mode & 0o111) !== 0,
encrypted: false,
byteOffset: null,
declaredSha256: null,
unpacked: false,
limitations:
kind === "symlink"
? ["Symlink target was not followed or disclosed."]
: [],
adapterKey: absolute,
...(kind === "file"
? {
sourceIdentity: { device: metadata.dev, inode: metadata.ino },
}
: {}),
};
if (kind === "directory" && (descendInto?.(path) ?? true))
directories.push(absolute);
}
} catch (cause: unknown) {
if (cause instanceof ArtifactReaderFailure) throw cause;
throw directoryIoFailure("read directory", directory, cause);
} finally {
// best-effort cleanup: directory-handle close must not mask traversal.
await handle.close().catch(() => undefined);
}
await withDirectoryIoContext("inspect directory", directory, () =>
assertContainedDirectory(root, directory),
);
}
}
async #resolveRoot(): Promise<string> {
return (this.#rootPromise ??= realpath(this.#rootPath)).catch(
(cause: unknown) => {
throw directoryIoFailure(
"resolve artifact root",
this.#rootPath,
cause,
);
},
);
}
async *#readDirectory(
directory: string,
pending: string[],
signal?: AbortSignal,
descendInto?: (path: string) => boolean,
): AsyncIterable<ArtifactEntry> {
const root = await this.#resolveRoot();
const handle = new OwnedDirectoryHandle(
await opendir(directory).catch((cause: unknown) => {
throw directoryIoFailure("open directory", directory, cause);
}),
);
this.#directories.add(handle);
const childDirectories: string[] = [];
let traversal:
| { readonly kind: "complete" }
| { readonly kind: "failed"; readonly cause: unknown } = {
kind: "complete",
};
try {
for (;;) {
const child = await handle.handle.read();
if (child === null) break;
abortIfNeeded(signal);
const absolute = join(directory, child.name);
const metadata = await lstat(absolute).catch((cause: unknown) => {
throw directoryIoFailure("inspect entry", absolute, cause);
});
const path = relative(root, absolute).split(sep).join("/");
const entry = artifactEntry(path, absolute, metadata);
if (entry === undefined) continue;
yield entry;
if (entry.kind === "directory" && (descendInto?.(path) ?? true))
childDirectories.push(absolute);
}
} catch (cause: unknown) {
traversal = {
kind: "failed",
cause:
cause instanceof ArtifactReaderFailure
? cause
: directoryIoFailure("read directory", directory, cause),
};
} finally {
await this.#finishDirectory(handle, directory, traversal);
}
if (traversal.kind === "failed") throw traversal.cause;
childDirectories.reverse();
pending.push(...childDirectories);
}
async #finishDirectory(
handle: OwnedDirectoryHandle,
path: string,
traversal:
| { readonly kind: "complete" }
| { readonly kind: "failed"; readonly cause: unknown },
): Promise<void> {
try {
await handle.close();
this.#directories.delete(handle);
} catch (cause: unknown) {
const closeFailure = directoryIoFailure("close directory", path, cause);
if (traversal.kind === "failed")
throw ArtifactReaderFailure.withCleanup(
traversal.cause,
ArtifactReaderFailure.cleanupObservation(closeFailure, path),
);
throw closeFailure;
directories.reverse();
pending.push(...directories);
}
}
@@ -148,16 +102,14 @@ export class DirectoryArtifactReader implements ArtifactReader {
"format",
"Only regular files can be opened",
);
const fileHandle = await open(
const handle = await open(
entry.adapterKey,
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
).catch((cause: unknown) => {
throw directoryIoFailure("open entry", entry.adapterKey, cause);
});
const owner = new OwnedFileHandle(fileHandle);
this.#files.set(owner, entry.adapterKey);
try {
const observed = await owner.handle.stat().catch((cause: unknown) => {
const observed = await handle.stat().catch((cause: unknown) => {
throw directoryIoFailure(
"inspect opened entry",
entry.adapterKey,
@@ -175,76 +127,16 @@ export class DirectoryArtifactReader implements ArtifactReader {
`Directory entry changed before open: ${entry.path}`,
);
}
abortIfNeeded(signal);
const source = Readable.from(
mapFileReadCancellation(owner.handle, signal),
{ objectMode: false },
);
source.once("close", () => {
void this.#closeFile(owner).catch(() => undefined);
});
return source;
return handle.createReadStream({ autoClose: true });
} catch (cause: unknown) {
try {
await this.#closeFile(owner);
} catch (closeCause: unknown) {
throw ArtifactReaderFailure.withCleanup(
cause,
ArtifactReaderFailure.cleanupObservation(
directoryIoFailure(
"close opened entry",
entry.adapterKey,
closeCause,
),
entry.adapterKey,
),
);
}
// best-effort cleanup: file-handle close must not mask the open failure.
await handle.close().catch(() => undefined);
throw cause;
}
}
async close(): Promise<void> {
const failures: unknown[] = [];
for (const [owner, path] of this.#files) {
try {
await this.#closeFile(owner);
} catch (cause: unknown) {
failures.push(directoryIoFailure("close opened entry", path, cause));
}
}
for (const owner of this.#directories) {
try {
await owner.close();
this.#directories.delete(owner);
} catch (cause: unknown) {
failures.push(
directoryIoFailure("close directory", owner.handle.path, cause),
);
}
}
if (failures.length > 0) {
const reason = failures.map(failureMessage).join("; ");
throw new ArtifactReaderFailure(
"io",
`Directory artifact cleanup failed: ${reason}`,
{
cause: new AggregateError(failures),
cleanup: {
reason,
resources: [
...this.#files.values(),
...[...this.#directories].map((owner) => owner.handle.path),
],
},
},
);
}
}
async #closeFile(owner: OwnedFileHandle<FileHandle>): Promise<void> {
await owner.close();
this.#files.delete(owner);
close(): Promise<void> {
return Promise.resolve();
}
provenance(): readonly [] {
@@ -252,42 +144,6 @@ export class DirectoryArtifactReader implements ArtifactReader {
}
}
const artifactEntry = (
path: string,
absolute: string,
metadata: Stats,
): ArtifactEntry | undefined => {
const kind = metadata.isSymbolicLink()
? "symlink"
: metadata.isDirectory()
? "directory"
: metadata.isFile()
? "file"
: undefined;
if (kind === undefined) return undefined;
return {
path,
kind,
declaredSize: kind === "file" ? metadata.size : null,
compressedSize: null,
executable: (metadata.mode & 0o111) !== 0,
encrypted: false,
byteOffset: null,
declaredSha256: null,
unpacked: false,
limitations:
kind === "symlink"
? ["Symlink target was not followed or disclosed."]
: [],
adapterKey: absolute,
...(kind === "file"
? {
sourceIdentity: { device: metadata.dev, inode: metadata.ino },
}
: {}),
};
};
const directoryIoFailure = (
operation: string,
path: string,
@@ -301,38 +157,13 @@ const directoryIoFailure = (
typeof cause.code === "string"
? ` (${cause.code})`
: "";
const detail = failureMessage(cause);
return new ArtifactReaderFailure(
"io",
`Could not ${operation} at ${path}${code}: ${detail}`,
`Could not ${operation} at ${path}${code}`,
{ cause },
);
};
const failureMessage = (cause: unknown): string =>
cause instanceof Error ? cause.message : String(cause);
const mapFileReadCancellation = async function* (
handle: FileHandle,
signal?: AbortSignal,
): AsyncGenerator<Buffer> {
try {
for await (const chunk of readFileHandleChunks(handle, { signal })) {
abortIfNeeded(signal);
yield chunk;
}
abortIfNeeded(signal);
} catch (cause: unknown) {
if (signal?.aborted === true)
throw new ArtifactReaderFailure(
"cancelled",
"Directory artifact read cancelled",
{ cause },
);
throw cause;
}
};
const withDirectoryIoContext = async <T>(
operation: string,
path: string,
+35 -78
View File
@@ -1,84 +1,41 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { readFile } from "node:fs/promises";
import { describe, expect, it, onTestFinished } from "vitest";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
import { CPU, fatImage, machoImage } from "./apple/MachoImage.fixture.js";
import { MachOSliceArtifactReader } from "./MachOSliceArtifactReader.js";
import { ok } from "../domain/result.js";
import { openRegularFile } from "../filesystem/RegularFile.js";
import type { NativeCommandRunner } from "../native/CommandRunner.js";
describe("MachOSliceArtifactReader", () => {
it("keeps a borrowed source usable after a cancelled slice read", async () => {
const root = await createTestTempDirectory("rea-slices-cancelled-");
const binary = join(root, "fat");
const x86 = machoImage({ cpu: CPU.x86_64 });
const arm = Buffer.concat([
Buffer.from(machoImage({ cpu: CPU.arm64 })),
Buffer.alloc(160_000, 0x5a),
]);
await writeFile(
binary,
fatImage([
{ cpu: CPU.x86_64, bytes: x86 },
{ cpu: CPU.arm64, bytes: arm },
]),
);
const handle = await openRegularFile(binary, { symlinks: "reject" });
const source = { handle, initial: await handle.stat() };
const runner: NativeCommandRunner = {
run: () =>
Promise.resolve(
ok({
tool: "lipo",
executable: "/usr/bin/lipo",
executableSha256: "1".repeat(64),
toolVersion: null,
versionReason: "fixture",
arguments: ["-detailed_info", binary],
stdout: `architecture x86_64\n cputype 16777223\n cpusubtype 3\n offset 4096\n size ${String(x86.length)}\n align 2^12 (4096)\narchitecture arm64\n cputype 16777228\n cpusubtype 0\n offset 8192\n size ${String(arm.length)}\n align 2^12 (4096)\n`,
stderr: "",
stdoutBytes: 1,
stderrBytes: 0,
exitCode: 0,
signal: null,
}),
),
};
const reader = new MachOSliceArtifactReader(binary, {}, runner, source);
onTestFinished(async () => {
await reader.close();
await handle.close();
});
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
const armEntry = entries.find((entry) => entry.path === "slices/arm64");
if (armEntry === undefined) throw new Error("Expected an arm64 slice");
const controller = new AbortController();
const cancelledRead = await reader.open(armEntry, controller.signal);
const iterator = cancelledRead[Symbol.asyncIterator]();
const firstChunk = await iterator.next();
expect(firstChunk.value).toHaveLength(64 * 1024);
controller.abort();
await expect(iterator.next()).rejects.toMatchObject({
reason: "cancelled",
});
const verifiedEntries = [];
for await (const entry of reader.entries()) verifiedEntries.push(entry);
const verifiedArmEntry = verifiedEntries.find(
(entry) => entry.path === "slices/arm64",
);
if (verifiedArmEntry === undefined)
throw new Error("Expected arm64 after re-verifying the borrowed source");
const verifiedChunks: Buffer[] = [];
const verifiedRead = await reader.open(verifiedArmEntry);
for await (const chunk of verifiedRead)
verifiedChunks.push(Buffer.from(chunk));
expect(Buffer.concat(verifiedChunks)).toEqual(arm);
/**
* Read a 32-bit FAT table directly. The host's /bin/ls changes between macOS
* releases, so the expected slice layout comes from the file itself.
*/
const fatSlices = async (
path: string,
): Promise<readonly (readonly [number, number])[]> => {
const bytes = await readFile(path);
expect(bytes.readUInt32BE(0)).toBe(0xca_fe_ba_be);
return Array.from({ length: bytes.readUInt32BE(4) }, (_, index) => {
const entry = 8 + index * 20;
return [bytes.readUInt32BE(entry + 8), bytes.readUInt32BE(entry + 12)];
});
};
describe("Mach-O slice reader with system lipo", () => {
it.skipIf(process.platform !== "darwin")(
"checks real /bin/ls lipo CPU symbols and ptrauth capabilities against the FAT table",
async () => {
const reader = new MachOSliceArtifactReader("/bin/ls", {});
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
expect(entries.map(({ path }) => path)).toEqual([
"slices/x86_64",
"slices/arm64e",
]);
expect(
entries.map(({ byteOffset, declaredSize }) => [
byteOffset,
declaredSize,
]),
).toEqual(await fatSlices("/bin/ls"));
},
);
});
+19 -56
View File
@@ -12,33 +12,25 @@ import {
type LipoArchitecture,
} from "../native/parsers/lipo.js";
import type { MachoSlice } from "../domain/apple/dylibResolution.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import { readMachoImage, type ReadAt } from "./apple/MachoLoadCommandReader.js";
import {
ArtifactReaderFailure,
copyArtifactEntry,
sameArtifactEntry,
type ArtifactEntry,
type ArtifactReader,
} from "./ArtifactReader.js";
import { streamChunkToBuffer } from "./StreamBytes.js";
import {
NonRegularFileReadError,
RegularFileAdmissionFailure,
openRegularFile,
sameRegularFileState,
type StableRegularFileDescriptor,
} from "../filesystem/RegularFile.js";
import { readFileHandleChunks } from "../filesystem/readFileHandleChunks.js";
/** Read-only universal Mach-O slice reader backed by native lipo metadata. */
export class MachOSliceArtifactReader implements ArtifactReader {
readonly format = "file" as const;
#command: ArtifactCommand | undefined;
#source: StableRegularFileDescriptor | undefined;
#ownedSource: OwnedFileHandle | undefined;
#pendingSource: Promise<StableRegularFileDescriptor> | undefined;
readonly #entries = new Map<string, ArtifactEntry>();
readonly #ownsSource: boolean;
#closed = false;
#closePromise: Promise<void> | undefined;
@@ -56,7 +48,6 @@ export class MachOSliceArtifactReader implements ArtifactReader {
}
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
this.#entries.clear();
const source = await this.#ensureSource();
await this.#verifySource(source);
const captured = await this.runner.run(
@@ -136,7 +127,7 @@ export class MachOSliceArtifactReader implements ArtifactReader {
"integrity",
`lipo reported an out-of-bounds Mach-O slice: ${architecture.name}`,
);
const entry: ArtifactEntry = {
yield {
path: `slices/${architecture.name}`,
kind: "slice",
declaredSize: sliceSize,
@@ -172,8 +163,6 @@ export class MachOSliceArtifactReader implements ArtifactReader {
],
adapterKey: `${String(offset)}:${String(sliceSize)}`,
};
this.#entries.set(entry.adapterKey, copyArtifactEntry(entry));
yield entry;
}
}
@@ -182,19 +171,14 @@ export class MachOSliceArtifactReader implements ArtifactReader {
return Promise.reject(
new ArtifactReaderFailure("cancelled", "Mach-O slice read cancelled"),
);
const produced = this.#entries.get(entry.adapterKey);
if (produced === undefined || !sameArtifactEntry(entry, produced))
throw new ArtifactReaderFailure(
"integrity",
"Mach-O slice entry metadata does not match this reader's inventory",
);
const offset = produced.byteOffset;
const size = produced.declaredSize;
const [offsetText, sizeText] = entry.adapterKey.split(":");
const offset = parseSliceKeyInteger(offsetText);
const size = parseSliceKeyInteger(sizeText);
if (
offset === null ||
size === null ||
!Number.isSafeInteger(offset) ||
!Number.isSafeInteger(size) ||
offset === null ||
size === null ||
offset < 0 ||
size <= 0
)
@@ -212,9 +196,10 @@ export class MachOSliceArtifactReader implements ArtifactReader {
"integrity",
`Mach-O slice range is outside the artifact: ${entry.path}`,
);
const sourceStream = readFileHandleChunks(source.handle, {
const sourceStream = source.handle.createReadStream({
start: offset,
end: offset + size - 1,
autoClose: false,
...(signal === undefined ? {} : { signal }),
});
const verifySource = () => this.#verifySource(source);
@@ -287,51 +272,23 @@ export class MachOSliceArtifactReader implements ArtifactReader {
}
async #acquireSource(): Promise<StableRegularFileDescriptor> {
let handle: FileHandle;
try {
handle = await openRegularFile(this.path, { symlinks: "reject" });
} catch (cause: unknown) {
if (!(cause instanceof RegularFileAdmissionFailure)) throw cause;
this.#ownedSource = cause.owner;
const primary =
cause.cause instanceof NonRegularFileReadError
? new ArtifactReaderFailure(
"format",
`Universal Mach-O source is not a regular file: ${this.path}`,
{ cause: cause.cause },
)
: cause.cause;
throw ArtifactReaderFailure.withCleanup(
primary,
ArtifactReaderFailure.cleanupObservation(cause.cleanupCause, this.path),
);
}
const owner = new OwnedFileHandle(handle);
this.#ownedSource = owner;
const handle = await openRegularFile(this.path, { symlinks: "reject" });
try {
const initial = await handle.stat();
const source = { handle, initial };
this.#source = source;
return source;
} catch (cause: unknown) {
try {
await owner.close();
this.#ownedSource = undefined;
} catch (cleanupCause: unknown) {
throw ArtifactReaderFailure.withCleanup(
cause,
ArtifactReaderFailure.cleanupObservation(cleanupCause, this.path),
);
}
await handle.close().catch(() => undefined);
throw cause;
}
}
async #closeSource(): Promise<void> {
await this.#pendingSource?.catch(() => undefined);
if (!this.#ownsSource || this.#ownedSource === undefined) return;
await this.#ownedSource.close();
this.#ownedSource = undefined;
if (!this.#ownsSource || this.#source === undefined) return;
const source = this.#source;
await source.handle.close();
this.#source = undefined;
}
@@ -400,3 +357,9 @@ const lipoMatchesSlice = (
const lipoNameMatches = (reported: string, observed: string): boolean =>
reported === observed ||
(observed === "arm64e" && /^arm64e\.[A-Za-z0-9_]+$/u.test(reported));
const parseSliceKeyInteger = (value: string | undefined): number | null => {
if (value === undefined || !/^\d+$/u.test(value)) return null;
const parsed = Number(value);
return Number.isSafeInteger(parsed) ? parsed : null;
};
+35 -34
View File
@@ -111,9 +111,7 @@ const createSystemHost = (
/** Read-only macOS DMG adapter that owns attachment and reverse-order detach. */
export class NativeDmgArtifactReader implements ArtifactReader {
readonly format = "file" as const;
private readonly host: NativeDmgHost;
readonly #provenance: ArtifactCommand[] = [];
#initialization: Promise<void> | undefined;
#directory: DirectoryArtifactReader | undefined;
#devices: string[] = [];
#inventoryConfirmedDevices = new Set<string>();
@@ -123,24 +121,33 @@ export class NativeDmgArtifactReader implements ArtifactReader {
#attachOutputReturned = false;
#attachMayHaveMounted = false;
#ownershipUncertainty: string | undefined;
#closed = false;
#closePromise: Promise<void> | undefined;
constructor(
private constructor(
private readonly path: string,
private readonly host: NativeDmgHost,
) {}
/** Verify and attach one image beneath an exclusively owned temporary root. */
static async create(
path: string,
environment: Readonly<NodeJS.ProcessEnv>,
signal?: AbortSignal,
host?: NativeDmgHost,
) {
): Promise<NativeDmgArtifactReader> {
if (process.platform !== "darwin" && host === undefined)
throw new ArtifactReaderFailure(
"unavailable",
"Native DMG traversal is available only on macOS",
);
this.host = host ?? createSystemHost(environment);
const reader = new NativeDmgArtifactReader(
path,
host ?? createSystemHost(environment),
);
await reader.attach(signal);
return reader;
}
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
await this.#ensureAttached(signal);
if (this.#directory === undefined)
throw new ArtifactReaderFailure("unavailable", "DMG is not attached");
const prefix = basename(this.path);
@@ -148,10 +155,11 @@ export class NativeDmgArtifactReader implements ArtifactReader {
yield { ...entry, path: `${prefix}/${entry.path}` };
}
async open(entry: ArtifactEntry, signal?: AbortSignal): Promise<Readable> {
await this.#ensureAttached(signal);
open(entry: ArtifactEntry, signal?: AbortSignal): Promise<Readable> {
if (this.#directory === undefined)
throw new ArtifactReaderFailure("unavailable", "DMG is not attached");
return Promise.reject(
new ArtifactReaderFailure("unavailable", "DMG is not attached"),
);
return this.#directory.open(entry, signal);
}
@@ -159,19 +167,7 @@ export class NativeDmgArtifactReader implements ArtifactReader {
return structuredClone(this.#provenance);
}
close(): Promise<void> {
this.#closed = true;
this.#closePromise ??= this.#closeOwnedResources().catch(
(cause: unknown) => {
this.#closePromise = undefined;
throw cause;
},
);
return this.#closePromise;
}
async #closeOwnedResources(): Promise<void> {
await this.#initialization?.catch(() => undefined);
async close(): Promise<void> {
let detachFailure = await this.#reconcileAttachState();
let remainingDevices: string[] = [];
for (const device of [...this.#devices].reverse()) {
@@ -285,16 +281,7 @@ export class NativeDmgArtifactReader implements ArtifactReader {
}
}
async #ensureAttached(signal?: AbortSignal): Promise<void> {
if (this.#closed)
throw new ArtifactReaderFailure("unavailable", "DMG reader is closed");
this.#initialization ??= this.#attach(signal);
await this.#initialization;
if (this.#closed)
throw new ArtifactReaderFailure("unavailable", "DMG reader is closed");
}
async #attach(signal?: AbortSignal): Promise<void> {
async attach(signal?: AbortSignal): Promise<void> {
await runChecked(this.host, ["verify", this.path], signal);
this.#provenance.push(command(["verify", this.path], ["read"]));
const baseline = await this.#readInfo();
@@ -374,6 +361,20 @@ export class NativeDmgArtifactReader implements ArtifactReader {
this.#attachMayHaveMounted = false;
this.#ownershipUncertainty = undefined;
}
let cleanupFailure: unknown;
try {
await this.close();
} catch (cleanupCause: unknown) {
cleanupFailure = cleanupCause;
}
if (cleanupFailure !== undefined)
throw ArtifactReaderFailure.withCleanup(
cause,
ArtifactReaderFailure.cleanupObservation(
cleanupFailure,
`DMG mount root ${this.#mountRoot ?? this.path}`,
),
);
throw cause;
}
}
-57
View File
@@ -1,57 +0,0 @@
import { expect, it, vi } from "vitest";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
it("shares one in-flight successful close between concurrent owners", async () => {
let resolveClose: (() => void) | undefined;
const file = {
fd: 17,
close: vi.fn(
() =>
new Promise<void>((resolve) => {
file.fd = -1;
resolveClose = resolve;
}),
),
};
const owner = new OwnedFileHandle(file);
const first = owner.close();
const second = owner.close();
await Promise.resolve();
expect(file.close).toHaveBeenCalledTimes(1);
resolveClose?.();
await expect(Promise.all([first, second])).resolves.toEqual([
undefined,
undefined,
]);
await expect(owner.close()).resolves.toBeUndefined();
expect(file.close).toHaveBeenCalledTimes(1);
});
it("shares one in-flight failed close and keeps its unconfirmed result sticky", async () => {
const failure = new Error("native close failed");
let rejectClose: (() => void) | undefined;
const file = {
fd: 17,
close: vi.fn(
() =>
new Promise<void>((_resolve, reject) => {
file.fd = -1;
rejectClose = () => reject(failure);
}),
),
};
const owner = new OwnedFileHandle(file);
const first = owner.close();
const second = owner.close();
await Promise.resolve();
expect(file.close).toHaveBeenCalledTimes(1);
rejectClose?.();
await expect(Promise.all([first, second])).rejects.toBe(failure);
await expect(owner.close()).rejects.toBe(failure);
expect(file.close).toHaveBeenCalledTimes(1);
});
@@ -1,68 +0,0 @@
import type { Stats } from "node:fs";
import type { FileHandle } from "node:fs/promises";
import { afterEach, expect, it, vi } from "vitest";
import {
NonRegularFileReadError,
openRegularFile,
RegularFileAdmissionFailure,
} from "../filesystem/RegularFile.js";
const { mockOpen } = vi.hoisted(() => ({ mockOpen: vi.fn() }));
vi.mock("node:fs/promises", async (importOriginal) => ({
...(await importOriginal<typeof import("node:fs/promises")>()),
open: mockOpen,
}));
afterEach(() => mockOpen.mockReset());
it.each(["cancellation after open", "non-regular metadata", "stat failure"])(
"retains the exact owner when close fails after %s",
async (failureCase) => {
const closeFailure = new Error("native close failed");
const statFailure = new Error("descriptor stat failed");
const cancellation = new Error("cancelled after open");
const controller = new AbortController();
const file = {
fd: 17,
stat: vi.fn(async () => {
if (failureCase === "cancellation after open") {
controller.abort(cancellation);
return { isFile: () => true } as Stats;
}
if (failureCase === "non-regular metadata")
return {
isFile: () => false,
isDirectory: () => false,
} as Stats;
throw statFailure;
}),
close: vi.fn(async () => {
file.fd = -1;
throw closeFailure;
}),
};
mockOpen.mockResolvedValue(file as unknown as FileHandle);
const cause = await openRegularFile("/selected/input", {
symlinks: "reject",
signal: controller.signal,
}).catch((failure: unknown) => failure);
expect(cause).toBeInstanceOf(RegularFileAdmissionFailure);
if (!(cause instanceof RegularFileAdmissionFailure))
throw new Error("Expected an admission failure that retains its owner");
expect(cause.owner.handle).toBe(file);
expect(cause.cleanupCause).toBe(closeFailure);
expect(file.close).toHaveBeenCalledTimes(1);
await expect(cause.owner.close()).rejects.toBe(closeFailure);
expect(file.close).toHaveBeenCalledTimes(1);
if (failureCase === "non-regular metadata")
expect(cause.cause).toBeInstanceOf(NonRegularFileReadError);
else if (failureCase === "stat failure")
expect(cause.cause).toBe(statFailure);
else expect(cause.cause).toBe(cancellation);
},
);
+142 -236
View File
@@ -5,11 +5,11 @@ import {
open,
readdir,
realpath,
rmdir,
type FileHandle,
} from "node:fs/promises";
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
import type { Readable } from "node:stream";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import { streamChunkToBuffer } from "./StreamBytes.js";
import {
@@ -18,14 +18,13 @@ import {
normalizeArtifactPath,
} from "./ArtifactPaths.js";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
import { SafeOutputTreeCreationFailure } from "./SafeOutputTreeCreationFailure.js";
import { hashOutputFile } from "./SafeOutputTreeReadback.js";
import { removeOwnedTree } from "./SafeOutputTreeCleanup.js";
import {
assertHandleIdentity,
assertFilePathIdentity,
assertPathIdentity,
isAbsent,
pathHasIdentity,
readDirectoryIdentity,
readFileIdentity,
replacedDirectory,
@@ -58,12 +57,9 @@ export type SafeOutputCleanup =
export class SafeOutputTree {
readonly #registry = new ArtifactPathRegistry();
readonly #outputRoot: string;
#rootIdentity: DirectoryIdentity | undefined;
readonly #rootIdentity: DirectoryIdentity;
readonly #nestedDirectories = new Map<string, DirectoryIdentity>();
readonly #unknownDirectories = new Set<string>();
readonly #ownedFiles = new Map<string, FileIdentity>();
readonly #openFiles = new Map<string, OwnedFileHandle>();
readonly #openHandles = new Set<OwnedFileHandle>();
#published = false;
#cleanup: SafeOutputCleanup = {
status: "not-required",
@@ -71,9 +67,11 @@ export class SafeOutputTree {
private constructor(
outputRoot: string,
rootIdentity: DirectoryIdentity,
private readonly platform: NodeJS.Platform,
) {
this.#outputRoot = outputRoot;
this.#rootIdentity = rootIdentity;
}
/**
@@ -115,52 +113,57 @@ export class SafeOutputTree {
);
throw cause;
});
const tree = new SafeOutputTree(canonicalOutput, platform);
let rootIdentity: DirectoryIdentity | undefined;
try {
const rootIdentity = await readDirectoryIdentity(canonicalOutput);
tree.#rootIdentity = rootIdentity;
rootIdentity = await readDirectoryIdentity(canonicalOutput);
if (platform !== "win32") {
const stagingHandle = tree.#trackHandle(
await open(
canonicalOutput,
constants.O_RDONLY | constants.O_DIRECTORY,
),
const stagingHandle = await open(
canonicalOutput,
constants.O_RDONLY | constants.O_DIRECTORY,
);
let setup:
| { readonly kind: "ready" }
| {
readonly kind: "failed";
readonly cause: unknown;
} = { kind: "ready" };
try {
await assertHandleIdentity(
stagingHandle.handle,
stagingHandle,
rootIdentity,
canonicalOutput,
);
await stagingHandle.handle.chmod(0o700);
} catch (cause: unknown) {
setup = { kind: "failed", cause };
await stagingHandle.chmod(0o700);
} finally {
await stagingHandle.close();
}
try {
await tree.#closeHandle(stagingHandle);
} catch (closeCause: unknown) {
if (setup.kind === "failed")
throw ArtifactReaderFailure.withCleanup(
setup.cause,
ArtifactReaderFailure.cleanupObservation(
closeCause,
canonicalOutput,
),
);
throw closeCause;
}
if (setup.kind === "failed") throw setup.cause;
}
await assertPathIdentity(canonicalOutput, rootIdentity);
return tree;
return new SafeOutputTree(canonicalOutput, rootIdentity, platform);
} catch (cause: unknown) {
throw new SafeOutputTreeCreationFailure(cause, tree);
let removalFailure: unknown;
let ownedRootAtPath = false;
try {
ownedRootAtPath =
rootIdentity !== undefined &&
(await pathHasIdentity(canonicalOutput, rootIdentity));
if (ownedRootAtPath) await rmdir(canonicalOutput);
else
removalFailure = new Error(
"Extraction output root identity changed during setup",
);
} catch (cleanupCause: unknown) {
removalFailure = cleanupCause;
}
let absent = false;
try {
absent = ownedRootAtPath && (await isAbsent(canonicalOutput));
} catch (cleanupCause: unknown) {
removalFailure ??= cleanupCause;
}
if (!absent)
throw ArtifactReaderFailure.withCleanup(cause, {
reason:
removalFailure instanceof Error
? removalFailure.message
: "Extraction output root ownership could not be verified after setup failure",
resources: [canonicalOutput],
});
throw cause;
}
}
@@ -168,11 +171,6 @@ export class SafeOutputTree {
return this.#outputRoot;
}
/** The output was durably committed, even if descriptor cleanup later failed. */
get published(): boolean {
return this.#published;
}
get cleanup(): SafeOutputCleanup {
return structuredClone(this.#cleanup);
}
@@ -213,62 +211,58 @@ export class SafeOutputTree {
{ cause },
);
});
const ownedHandle = this.#trackHandle(handle);
this.#openFiles.set(destination, ownedHandle);
const fileIdentity = await readFileIdentity(
ownedHandle.handle,
destination,
const fileIdentity = await readFileIdentity(handle, destination).catch(
async (cause: unknown) => {
await handle.close().catch(() => undefined);
throw cause;
},
);
await assertFilePathIdentity(destination, fileIdentity);
this.#ownedFiles.set(destination, fileIdentity);
const hash = createHash("sha256");
let bytes = 0;
await this.#assertLineage(lineage);
for await (const raw of source) {
abortIfNeeded(signal);
const chunk = streamChunkToBuffer(raw);
if (chunk.length > expected.bytes - bytes)
try {
await this.#assertLineage(lineage);
for await (const raw of source) {
abortIfNeeded(signal);
const chunk = streamChunkToBuffer(raw);
if (chunk.length > expected.bytes - bytes)
throw new ArtifactReaderFailure(
"integrity",
`Extracted content exceeds the inventoried size: ${path}`,
);
bytes += chunk.length;
hash.update(chunk);
await writeAll(handle, chunk);
}
if (bytes !== expected.bytes)
throw new ArtifactReaderFailure(
"integrity",
`Extracted content exceeds the inventoried size: ${path}`,
`Extracted content size disagrees with inventory: ${path}`,
);
bytes += chunk.length;
hash.update(chunk);
await writeAll(ownedHandle.handle, chunk);
const sha256 = hash.digest("hex");
if (sha256 !== expected.sha256)
throw new ArtifactReaderFailure(
"integrity",
`Extracted content disagrees with inventory: ${path}`,
);
await this.#assertLineage(lineage);
await assertFilePathIdentity(destination, fileIdentity);
await handle.sync();
await handle.close();
const readback = await hashFile(destination, bytes, signal);
await this.#assertLineage(lineage);
await assertFilePathIdentity(destination, fileIdentity);
if (readback.sha256 !== sha256 || readback.bytes !== bytes)
throw new ArtifactReaderFailure(
"integrity",
`Durable readback verification failed: ${path}`,
);
return { relativePath: path, sha256, bytesWritten: bytes };
} catch (cause: unknown) {
// best-effort cleanup: file-handle close must not mask the write failure.
await handle.close().catch(() => undefined);
throw cause;
}
if (bytes !== expected.bytes)
throw new ArtifactReaderFailure(
"integrity",
`Extracted content size disagrees with inventory: ${path}`,
);
const sha256 = hash.digest("hex");
if (sha256 !== expected.sha256)
throw new ArtifactReaderFailure(
"integrity",
`Extracted content disagrees with inventory: ${path}`,
);
await this.#assertLineage(lineage);
await assertFilePathIdentity(destination, fileIdentity);
await ownedHandle.handle.sync();
await this.#closeFileHandle(destination, ownedHandle);
const readbackHandle = this.#trackHandle(
await open(destination, constants.O_RDONLY | constants.O_NOFOLLOW),
);
const readback = await hashOutputFile(
readbackHandle,
destination,
fileIdentity,
{ maximum: bytes, signal },
);
await this.#closeHandle(readbackHandle);
await this.#assertLineage(lineage);
await assertFilePathIdentity(destination, fileIdentity);
if (readback.sha256 !== sha256 || readback.bytes !== bytes)
throw new ArtifactReaderFailure(
"integrity",
`Durable readback verification failed: ${path}`,
);
return { relativePath: path, sha256, bytesWritten: bytes };
} catch (cause: unknown) {
try {
source.destroy();
@@ -288,80 +282,34 @@ export class SafeOutputTree {
this.#published = true;
return;
}
const parent = this.#trackHandle(
await open(
dirname(this.#outputRoot),
constants.O_RDONLY | constants.O_DIRECTORY,
),
const parent = await open(
dirname(this.#outputRoot),
constants.O_RDONLY | constants.O_DIRECTORY,
);
let output: OwnedFileHandle | undefined;
let sync:
| { readonly kind: "synced" }
| {
readonly kind: "failed";
readonly cause: unknown;
} = { kind: "synced" };
let output: FileHandle | undefined;
try {
output = this.#trackHandle(
await open(
this.#outputRoot,
constants.O_RDONLY | constants.O_DIRECTORY,
),
);
await assertHandleIdentity(
output.handle,
this.#requireRootIdentity(),
output = await open(
this.#outputRoot,
constants.O_RDONLY | constants.O_DIRECTORY,
);
await output.handle.sync();
await parent.handle.sync();
await assertHandleIdentity(output, this.#rootIdentity, this.#outputRoot);
await output.sync();
await parent.sync();
this.#published = true;
} catch (cause: unknown) {
sync = { kind: "failed", cause };
}
const closeResults = await Promise.allSettled(
[parent, output]
.filter(isDefined)
.map((handle) => this.#closeHandle(handle)),
);
const closeFailures = closeResults
.filter(isRejected)
.map(({ reason }) => reason);
if (closeFailures.length > 0) {
const closeFailure = new AggregateError(
closeFailures,
"Extraction output directory handles could not be closed",
);
const cleanup = ArtifactReaderFailure.cleanupObservation(
closeFailure,
this.#outputRoot,
);
if (sync.kind === "failed")
throw ArtifactReaderFailure.withCleanup(
new ArtifactReaderFailure(
"path",
"Could not durably sync extraction output",
{ cause: sync.cause },
),
cleanup,
);
throw ArtifactReaderFailure.withCleanup(closeFailure, cleanup);
}
if (sync.kind === "failed")
throw new ArtifactReaderFailure(
"path",
"Could not durably sync extraction output",
{ cause: sync.cause },
{ cause },
);
} finally {
await Promise.allSettled([parent.close(), output?.close()]);
}
}
/** Remove only this operation's unsealed tree and verify absence. */
async rollback(): Promise<SafeOutputCleanup> {
if (this.#published) {
await this.#closePendingHandles();
return structuredClone(this.#cleanup);
}
if (this.#cleanup.status === "complete")
if (this.#published || this.#cleanup.status === "complete")
return structuredClone(this.#cleanup);
this.#cleanup = {
status: "incomplete",
@@ -369,12 +317,10 @@ export class SafeOutputTree {
};
let removalFailure: unknown;
try {
await this.#admitPendingFiles();
await this.#closePendingHandles();
await this.#assertOwnedDirectories();
await removeOwnedTree({
outputRoot: this.#outputRoot,
rootIdentity: this.#requireRootIdentity(),
rootIdentity: this.#rootIdentity,
directories: this.#nestedDirectories,
files: this.#ownedFiles,
});
@@ -416,10 +362,10 @@ export class SafeOutputTree {
let current = this.#outputRoot;
let logicalParent = "";
const lineage: DirectoryLineageEntry[] = [
{ path: this.#outputRoot, identity: this.#requireRootIdentity() },
{ path: this.#outputRoot, identity: this.#rootIdentity },
];
if (parts.length === 0)
await assertPathIdentity(this.#outputRoot, this.#requireRootIdentity());
await assertPathIdentity(this.#outputRoot, this.#rootIdentity);
for (const part of parts) {
const parent = lineage.at(-1);
if (parent === undefined) throw replacedDirectory(this.#outputRoot);
@@ -438,13 +384,8 @@ export class SafeOutputTree {
if (identity === undefined) throw replacedDirectory(current);
await assertPathIdentity(current, identity);
} else {
try {
const identity = await readDirectoryIdentity(current);
this.#nestedDirectories.set(current, identity);
} catch (cause: unknown) {
this.#unknownDirectories.add(current);
throw cause;
}
const identity = await readDirectoryIdentity(current);
this.#nestedDirectories.set(current, identity);
}
await assertPathIdentity(parent.path, parent.identity);
const identity = this.#nestedDirectories.get(current);
@@ -464,24 +405,9 @@ export class SafeOutputTree {
}
async #assertOwnedDirectories(): Promise<void> {
const rootIdentity = this.#requireRootIdentity();
await assertPathIdentity(this.#outputRoot, rootIdentity);
await assertPathIdentity(this.#outputRoot, this.#rootIdentity);
for (const [path, identity] of this.#nestedDirectories)
await assertPathIdentity(path, identity);
if (this.#unknownDirectories.size > 0)
throw new ArtifactReaderFailure(
"path",
`Extraction directory ownership is unknown: ${[...this.#unknownDirectories].join(", ")}`,
);
}
#requireRootIdentity(): DirectoryIdentity {
if (this.#rootIdentity === undefined)
throw new ArtifactReaderFailure(
"path",
`Extraction output root identity is unknown: ${this.#outputRoot}`,
);
return this.#rootIdentity;
}
#assertWritable(): void {
@@ -496,59 +422,39 @@ export class SafeOutputTree {
"Extraction tree cleanup has already started",
);
}
#trackHandle(handle: FileHandle): OwnedFileHandle {
const owner = new OwnedFileHandle(handle);
this.#openHandles.add(owner);
return owner;
}
async #closeHandle(owner: OwnedFileHandle): Promise<void> {
await owner.close();
this.#openHandles.delete(owner);
}
async #closePendingHandles(): Promise<void> {
const failures: unknown[] = [];
for (const owner of this.#openHandles) {
try {
await this.#closeHandle(owner);
} catch (cause: unknown) {
failures.push(cause);
}
}
if (failures.length > 0)
throw new AggregateError(failures, "Output tree handles remain open");
}
async #closeFileHandle(path: string, owner: OwnedFileHandle): Promise<void> {
await this.#closeHandle(owner);
this.#openFiles.delete(path);
}
async #admitPendingFiles(): Promise<void> {
for (const [path, owner] of this.#openFiles) {
let identity = this.#ownedFiles.get(path);
if (identity === undefined) {
identity = await readFileIdentity(owner.handle, path);
await assertFilePathIdentity(path, identity);
this.#ownedFiles.set(path, identity);
}
}
}
}
const isDefined = <T>(value: T | undefined): value is T => value !== undefined;
const isRejected = (
result: PromiseSettledResult<void>,
): result is PromiseRejectedResult => result.status === "rejected";
type DirectoryLineageEntry = {
readonly path: string;
readonly identity: DirectoryIdentity;
};
const hashFile = async (
path: string,
maximum: number,
signal?: AbortSignal,
): Promise<{ readonly sha256: string; readonly bytes: number }> => {
const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
const hash = createHash("sha256");
let bytes = 0;
try {
for await (const raw of handle.createReadStream({ autoClose: false })) {
abortIfNeeded(signal);
const chunk = streamChunkToBuffer(raw);
bytes += chunk.length;
if (bytes > maximum)
throw new ArtifactReaderFailure(
"integrity",
"Readback exceeded the bytes written",
);
hash.update(chunk);
}
} finally {
await handle.close();
}
return { sha256: hash.digest("hex"), bytes };
};
const writeAll = async (
handle: Awaited<ReturnType<typeof open>>,
chunk: Buffer,
@@ -569,14 +475,6 @@ const writeAll = async (
}
};
const abortIfNeeded = (signal?: AbortSignal): void => {
if (signal?.aborted === true)
throw new ArtifactReaderFailure(
"cancelled",
"Artifact extraction cancelled",
);
};
const isAlreadyExists = (cause: unknown): boolean =>
cause instanceof Error && "code" in cause && cause.code === "EEXIST";
@@ -596,3 +494,11 @@ const throwIfDestinationCaseCollision = async (
cause === undefined ? undefined : { cause },
);
};
const abortIfNeeded = (signal?: AbortSignal): void => {
if (signal?.aborted === true)
throw new ArtifactReaderFailure(
"cancelled",
"Artifact extraction cancelled",
);
};
@@ -1,31 +0,0 @@
import { ArtifactReaderFailure } from "./ArtifactReader.js";
import type { SafeOutputTree } from "./SafeOutputTree.js";
/** Setup failed after this tree was acquired; callers still own this exact tree. */
export class SafeOutputTreeCreationFailure extends ArtifactReaderFailure {
readonly tree: SafeOutputTree;
constructor(cause: unknown, tree: SafeOutputTree) {
const primary =
cause instanceof ArtifactReaderFailure
? cause
: new ArtifactReaderFailure("io", errorMessage(cause), { cause });
super(
primary.reason,
primary.message,
{
cause: primary,
...(primary.cleanup === undefined ? {} : { cleanup: primary.cleanup }),
...(primary.partialObservation === undefined
? {}
: { partialObservation: primary.partialObservation }),
},
primary.details,
);
this.name = "SafeOutputTreeCreationFailure";
this.tree = tree;
}
}
const errorMessage = (cause: unknown): string =>
cause instanceof Error ? cause.message : String(cause);
+14
View File
@@ -71,6 +71,20 @@ export const assertFilePathIdentity = async (
);
};
export const pathHasIdentity = async (
path: string,
expected: DirectoryIdentity,
): Promise<boolean> => {
try {
await assertPathIdentity(path, expected);
return true;
} catch (cause: unknown) {
if (isNotFound(cause) || cause instanceof ArtifactReaderFailure)
return false;
throw cause;
}
};
export const isAbsent = async (path: string): Promise<boolean> =>
lstat(path).then(
() => false,
-62
View File
@@ -1,62 +0,0 @@
import { createHash } from "node:crypto";
import type { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import { readFileHandleChunks } from "../filesystem/readFileHandleChunks.js";
import { streamChunkToBuffer } from "./StreamBytes.js";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
import {
assertFilePathIdentity,
readFileIdentity,
type FileIdentity,
} from "./SafeOutputTreeIdentity.js";
/** Hash one retained readback descriptor and confirm it still names the output file. */
export const hashOutputFile = async (
owner: OwnedFileHandle,
path: string,
identity: FileIdentity,
options: {
readonly maximum: number;
readonly signal?: AbortSignal | undefined;
},
): Promise<{ readonly sha256: string; readonly bytes: number }> => {
const admittedIdentity = await readFileIdentity(owner.handle, path);
await assertFilePathIdentity(path, identity);
if (
admittedIdentity.dev !== identity.dev ||
admittedIdentity.ino !== identity.ino
)
throw new ArtifactReaderFailure(
"path",
`Extraction file identity changed: ${path}`,
);
const hash = createHash("sha256");
let bytes = 0;
try {
for await (const raw of readFileHandleChunks(owner.handle, options)) {
if (options.signal?.aborted === true)
throw new ArtifactReaderFailure(
"cancelled",
"Artifact extraction cancelled",
);
const chunk = streamChunkToBuffer(raw);
bytes += chunk.length;
if (bytes > options.maximum)
throw new ArtifactReaderFailure(
"integrity",
"Readback exceeded the bytes written",
);
hash.update(chunk);
}
} catch (cause: unknown) {
if (options.signal?.aborted === true)
throw new ArtifactReaderFailure(
"cancelled",
"Artifact extraction cancelled",
{ cause },
);
throw cause;
}
await assertFilePathIdentity(path, identity);
return { sha256: hash.digest("hex"), bytes };
};
+22 -67
View File
@@ -6,16 +6,12 @@ import { Reader, ZipReader, type Entry, type FileEntry } from "@zip.js/zip.js";
import {
ArtifactReaderFailure,
copyArtifactEntry,
sameArtifactEntry,
type ArtifactEntry,
type ArtifactReader,
} from "./ArtifactReader.js";
import type { ZipPackageFormat } from "../domain/zipPackageFormat.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import {
NonRegularFileReadError,
RegularFileAdmissionFailure,
openRegularFile,
sameRegularFileState,
type StableRegularFileDescriptor,
@@ -23,7 +19,6 @@ import {
class NodeFileReader extends Reader<string> {
#handle: FileHandle | undefined;
#owner: OwnedFileHandle | undefined;
#initPromise: Promise<void> | undefined;
readonly #ownsHandle: boolean;
@@ -43,30 +38,10 @@ class NodeFileReader extends Reader<string> {
async #initialize(): Promise<void> {
try {
const handle =
this.#handle =
this.admitted?.handle ??
(await openRegularFile(this.path, { symlinks: "reject" }));
this.#handle = handle;
if (this.#ownsHandle) this.#owner = new OwnedFileHandle(handle);
} catch (cause: unknown) {
if (cause instanceof RegularFileAdmissionFailure) {
this.#owner = cause.owner;
const primary =
cause.cause instanceof NonRegularFileReadError
? new ArtifactReaderFailure(
"format",
`ZIP source is not a regular file: ${this.path}`,
{ cause: cause.cause },
)
: cause.cause;
throw ArtifactReaderFailure.withCleanup(
primary,
ArtifactReaderFailure.cleanupObservation(
cause.cleanupCause,
this.path,
),
);
}
if (cause instanceof NonRegularFileReadError)
throw new ArtifactReaderFailure(
"format",
@@ -111,9 +86,8 @@ class NodeFileReader extends Reader<string> {
async closeHandle(): Promise<void> {
if (!this.#ownsHandle) return;
await this.#initPromise?.catch(() => undefined);
if (this.#owner === undefined) return;
await this.#owner.close();
this.#owner = undefined;
if (this.#handle === undefined) return;
await this.#handle.close();
this.#handle = undefined;
}
}
@@ -123,10 +97,7 @@ export class ZipArtifactReader implements ArtifactReader {
readonly format: ZipPackageFormat;
readonly #source: NodeFileReader;
readonly #reader: ZipReader<string>;
readonly #entries = new Map<
string,
{ readonly source: Entry; readonly metadata: ArtifactEntry }
>();
readonly #entries = new Map<string, Entry>();
/** Optionally bound each metadata read before allocating its backing buffer. */
constructor(
@@ -149,38 +120,39 @@ export class ZipArtifactReader implements ArtifactReader {
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
for await (const entry of this.#reader.getEntriesGenerator()) {
abortIfNeeded(signal);
const metadata = projectZipEntry(entry);
this.#entries.set(entry.filename, {
source: entry,
metadata: copyArtifactEntry(metadata),
});
yield metadata;
this.#entries.set(entry.filename, entry);
const symlink = isSymlink(entry);
yield {
path: entry.filename,
kind: entry.directory ? "directory" : symlink ? "symlink" : "file",
declaredSize: entry.directory ? null : entry.uncompressedSize,
compressedSize: entry.directory ? null : entry.compressedSize,
executable: entry.executable,
encrypted: entry.encrypted,
byteOffset: null,
declaredSha256: null,
unpacked: false,
limitations: symlink ? ["Archive symlink target was not read."] : [],
adapterKey: entry.filename,
};
}
}
open(entry: ArtifactEntry, signal?: AbortSignal): Promise<Readable> {
abortIfNeeded(signal);
const stored = this.#entries.get(entry.adapterKey);
if (stored === undefined || !sameArtifactEntry(entry, stored.metadata))
return Promise.reject(
new ArtifactReaderFailure(
"integrity",
"ZIP entry metadata does not match this reader's inventory",
),
);
const source = stored.source;
if (source.directory || isSymlink(source))
if (stored === undefined || stored.directory || isSymlink(stored))
return Promise.reject(
new ArtifactReaderFailure("format", "ZIP entry is not a regular file"),
);
if (source.encrypted)
if (stored.encrypted)
return Promise.reject(
new ArtifactReaderFailure(
"unavailable",
"Encrypted ZIP entry is unsupported",
),
);
return Promise.resolve(extractStream(source, signal));
return Promise.resolve(extractStream(stored, signal));
}
async close(): Promise<void> {
@@ -194,23 +166,6 @@ export class ZipArtifactReader implements ArtifactReader {
}
}
const projectZipEntry = (entry: Entry): ArtifactEntry => {
const symlink = isSymlink(entry);
return {
path: entry.filename,
kind: entry.directory ? "directory" : symlink ? "symlink" : "file",
declaredSize: entry.directory ? null : entry.uncompressedSize,
compressedSize: entry.directory ? null : entry.compressedSize,
executable: entry.executable,
encrypted: entry.encrypted,
byteOffset: null,
declaredSha256: null,
unpacked: false,
limitations: symlink ? ["Archive symlink target was not read."] : [],
adapterKey: entry.filename,
};
};
const extractStream = (entry: FileEntry, signal?: AbortSignal): Readable => {
const output = new PassThrough();
const controller = new AbortController();
+90 -155
View File
@@ -15,7 +15,6 @@ import {
import { abortIfNeeded } from "../ArtifactHash.js";
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
import { SafeOutputTree } from "../SafeOutputTree.js";
import { SafeOutputTreeCreationFailure } from "../SafeOutputTreeCreationFailure.js";
import { ZipArtifactReader } from "../ZipArtifactReader.js";
import { MachOSliceArtifactReader } from "../MachOSliceArtifactReader.js";
import {
@@ -27,13 +26,9 @@ import {
type IntegrityContradiction,
} from "../../domain/artifactGraph.js";
import { AnalysisUnsupportedTargetError } from "../../domain/analysisErrorCore.js";
import {
type ArtifactResourceOwner,
type ArtifactResourceScope,
} from "../ArtifactResourceScope.js";
import type { BinaryTarget } from "../../domain/binaryTargetTypes.js";
import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySnapshot.js";
import { scanArtifactInventoryInScope } from "../inventory/ArtifactInventory.js";
import { scanArtifactInventory } from "../inventory/ArtifactInventory.js";
import type { ArtifactIntegrityPolicyName } from "../../domain/artifactIntegrityPolicy.js";
/** Local extraction input with the output root chosen by the adapter. */
@@ -43,36 +38,23 @@ export interface ArtifactExtractionInput {
readonly outputRoot: string;
readonly environment: Readonly<NodeJS.ProcessEnv>;
readonly integrityPolicy: ArtifactIntegrityPolicyName;
readonly resourceScope: ArtifactResourceScope;
}
/** Extract every regular inventory occurrence into an exclusively owned absent root. */
export const extractArtifact = async (
input: ArtifactExtractionInput,
signal?: AbortSignal,
): Promise<ArtifactExtractionResult> =>
input.resourceScope.run(() => extractArtifactInScope(input, signal));
const extractArtifactInScope = async (
input: ArtifactExtractionInput,
signal?: AbortSignal,
): Promise<ArtifactExtractionResult> => {
// Cancellation wins over every later refusal, including unsupported formats.
abortIfNeeded(signal);
const sourcePath = await realpath(input.inputPath);
await requireExtractableFormat(sourcePath, input);
const snapshot = await scanArtifactInventoryInScope(sourcePath, {
resourceScope: input.resourceScope,
const snapshot = await scanArtifactInventory(sourcePath, {
signal,
environment: input.environment,
integrity: { mode: input.integrityPolicy },
});
return materializeArtifactInventoryInScope(
input,
sourcePath,
snapshot,
signal,
);
return materializeArtifactInventory(input, sourcePath, snapshot, signal);
};
/** Materialize a scanned inventory, verifying every current occurrence against it. */
@@ -81,17 +63,6 @@ export const materializeArtifactInventory = async (
sourcePath: string,
snapshot: ArtifactInventorySnapshot,
signal?: AbortSignal,
): Promise<ArtifactExtractionResult> => {
return input.resourceScope.run(() =>
materializeArtifactInventoryInScope(input, sourcePath, snapshot, signal),
);
};
const materializeArtifactInventoryInScope = async (
input: ArtifactExtractionInput,
sourcePath: string,
snapshot: ArtifactInventorySnapshot,
signal?: AbortSignal,
): Promise<ArtifactExtractionResult> => {
abortIfNeeded(signal);
const selectedOccurrences = snapshot.occurrences.filter(
@@ -214,147 +185,111 @@ const materializeSelection = async ({
selected.map((item) => [item.occurrence.logical_path, item]),
);
const reader = await createReader(sourcePath, input);
const readerOwner: ArtifactResourceOwner = {
kind: "reader" as const,
reader,
resource: `artifact reader for ${sourcePath}`,
};
let localReaderOwner: ArtifactResourceOwner | undefined = readerOwner;
let output: SafeOutputTree | undefined;
let completed: ArtifactExtractionResult | undefined;
let readerCloseAttempted = false;
let readerClosed = false;
const extracted: ExtractedOccurrence[] = [];
try {
try {
output = await SafeOutputTree.create(input.outputRoot);
} catch (cause: unknown) {
if (cause instanceof SafeOutputTreeCreationFailure) output = cause.tree;
throw cause;
}
await writeSelectedEntries({ reader, output, byPath, extracted, signal });
localReaderOwner = undefined;
const closeAttempt = await input.resourceScope.release(readerOwner);
if (closeAttempt.kind === "failed")
throw ArtifactReaderFailure.withCleanup(
closeAttempt.cause,
ArtifactReaderFailure.cleanupObservation(
closeAttempt.cause,
readerOwner.resource,
),
output = await SafeOutputTree.create(input.outputRoot);
const registry = new ArtifactPathRegistry();
for await (const entry of reader.entries(signal)) {
const path = normalizeArtifactPath(entry.path);
registry.add(path, entry.kind);
const selectedItem = byPath.get(path);
if (selectedItem === undefined) {
if (entry.kind === "file" || entry.kind === "slice")
throw new ArtifactReaderFailure(
"integrity",
`Regular artifact entry is missing from inventory: ${path}`,
);
continue;
}
preflight(entry);
const stream = await reader.open(entry, signal);
const written = await output.write(
path,
stream,
{
sha256: selectedItem.node.sha256,
bytes: selectedItem.node.size,
},
signal,
);
extracted.push({
artifact_id: selectedItem.node.artifact_id,
relative_path: written.relativePath,
sha256: written.sha256,
bytes_written: written.bytesWritten,
created: true,
});
byPath.delete(path);
}
if (byPath.size > 0)
throw new ArtifactReaderFailure(
"integrity",
`Inventoried regular artifact entries were not materialized: ${[...byPath.keys()].sort(compareUnicodeCodePoints).join(", ")}`,
);
readerCloseAttempted = true;
await reader.close();
readerClosed = true;
extracted.sort((left, right) =>
compareUnicodeCodePoints(left.relative_path, right.relative_path),
);
completed = createExtractionResult(input, inventory, selected, extracted);
await output.commit();
return completed;
} catch (cause: unknown) {
const cleanupFailures = await releaseExtractionOwners(
input.resourceScope,
localReaderOwner,
output,
input.outputRoot,
const result = createExtractionResult(
input,
inventory,
selected,
extracted,
);
await output.commit();
return result;
} catch (cause: unknown) {
const cleanupFailures: {
readonly cause: unknown;
readonly resource: string;
}[] = [];
if (readerCloseAttempted && !readerClosed)
cleanupFailures.push({
cause,
resource: `artifact reader for ${sourcePath}`,
});
if (!readerCloseAttempted) {
try {
readerCloseAttempted = true;
await reader.close();
} catch (cleanupCause: unknown) {
cleanupFailures.push({
cause: cleanupCause,
resource: `artifact reader for ${sourcePath}`,
});
}
}
if (output !== undefined) {
try {
await output.rollback();
} catch (cleanupCause: unknown) {
cleanupFailures.push({
cause: cleanupCause,
resource: input.outputRoot,
});
}
}
if (cleanupFailures.length > 0) {
const observations = cleanupFailures.map(
({ cause: cleanupCause, resource }) =>
ArtifactReaderFailure.cleanupObservation(cleanupCause, resource),
);
throw ArtifactReaderFailure.withCleanup(
cause,
{
reason: observations.map(({ reason }) => reason).join("; "),
resources: [
...new Set(observations.flatMap(({ resources }) => resources)),
],
},
output?.published === true && completed !== undefined
? { kind: "artifact-extraction", extraction: completed }
: undefined,
);
throw ArtifactReaderFailure.withCleanup(cause, {
reason: observations.map(({ reason }) => reason).join("; "),
resources: [
...new Set(observations.flatMap(({ resources }) => resources)),
],
});
}
if (output?.published === true && completed !== undefined) return completed;
throw cause;
}
};
const writeSelectedEntries = async ({
reader,
output,
byPath,
extracted,
signal,
}: {
readonly reader: ArtifactReader;
readonly output: SafeOutputTree;
readonly byPath: Map<string, SelectedOccurrence>;
readonly extracted: ExtractedOccurrence[];
readonly signal: AbortSignal | undefined;
}): Promise<void> => {
const registry = new ArtifactPathRegistry();
for await (const entry of reader.entries(signal)) {
const path = normalizeArtifactPath(entry.path);
registry.add(path, entry.kind);
const selectedItem = byPath.get(path);
if (selectedItem === undefined) {
if (entry.kind === "file" || entry.kind === "slice")
throw new ArtifactReaderFailure(
"integrity",
`Regular artifact entry is missing from inventory: ${path}`,
);
continue;
}
preflight(entry);
const stream = await reader.open(entry, signal);
const written = await output.write(
path,
stream,
{
sha256: selectedItem.node.sha256,
bytes: selectedItem.node.size,
},
signal,
);
extracted.push({
artifact_id: selectedItem.node.artifact_id,
relative_path: written.relativePath,
sha256: written.sha256,
bytes_written: written.bytesWritten,
created: true,
});
byPath.delete(path);
}
if (byPath.size > 0)
throw new ArtifactReaderFailure(
"integrity",
`Inventoried regular artifact entries were not materialized: ${[...byPath.keys()].sort(compareUnicodeCodePoints).join(", ")}`,
);
};
const releaseExtractionOwners = async (
resourceScope: ArtifactResourceScope,
readerOwner: ArtifactResourceOwner | undefined,
output: SafeOutputTree | undefined,
outputRoot: string,
): Promise<{ readonly cause: unknown; readonly resource: string }[]> => {
const failures: { readonly cause: unknown; readonly resource: string }[] = [];
if (readerOwner !== undefined) {
const attempt = await resourceScope.release(readerOwner);
if (attempt.kind === "failed")
failures.push({ cause: attempt.cause, resource: readerOwner.resource });
}
if (output !== undefined) {
const owner: ArtifactResourceOwner = {
kind: "output-tree",
tree: output,
resource: outputRoot,
};
const attempt = await resourceScope.release(owner);
if (attempt.kind === "failed")
failures.push({ cause: attempt.cause, resource: owner.resource });
}
return failures;
};
const createExtractionResult = (
input: ArtifactExtractionInput,
inventory: ExtractionInventory,
+4 -12
View File
@@ -5,14 +5,14 @@ import {
type ArtifactInventoryResult,
} from "../../domain/artifactGraph.js";
import { abortIfNeeded } from "../ArtifactHash.js";
import { scanCanonicalArtifactInventoryInScope } from "./scanCanonical.js";
import { scanCanonicalArtifactInventory } from "./scanCanonical.js";
import type { ArtifactInventoryOptions } from "./types.js";
import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySnapshot.js";
/** Inventory one local artifact and return every graph collection inline. */
export const inventoryArtifact = async (
inputPath: string,
options: ArtifactInventoryOptions,
options: ArtifactInventoryOptions = {},
): Promise<ArtifactInventoryResult> => {
const snapshot = await scanArtifactInventory(inputPath, options);
return artifactInventoryResultSchema.parse(snapshot);
@@ -21,17 +21,9 @@ export const inventoryArtifact = async (
/** Scan an artifact once and retain the complete immutable graph for projection. */
export const scanArtifactInventory = async (
inputPath: string,
options: ArtifactInventoryOptions,
): Promise<ArtifactInventorySnapshot> =>
options.resourceScope.run(() =>
scanArtifactInventoryInScope(inputPath, options),
);
export const scanArtifactInventoryInScope = async (
inputPath: string,
options: ArtifactInventoryOptions,
options: ArtifactInventoryOptions = {},
): Promise<ArtifactInventorySnapshot> => {
abortIfNeeded(options.signal);
const path = await realpath(inputPath);
return scanCanonicalArtifactInventoryInScope(path, options);
return scanCanonicalArtifactInventory(path, options);
};
@@ -4,7 +4,7 @@ import { join } from "node:path";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { inventoryArtifact } from "../../../tests/fixtures/artifactInventory.js";
import { inventoryArtifact } from "./ArtifactInventory.js";
import { compareArtifacts } from "../../domain/artifactComparison.js";
import { projectAppleApplication } from "../../domain/apple/appleApplication.js";
import { createEvidence } from "../../domain/evidence.js";
+46 -83
View File
@@ -1,8 +1,11 @@
import { sameRegularFileState } from "../../filesystem/RegularFile.js";
import {
NonRegularFileReadError,
openRegularFile,
sameRegularFileState,
} from "../../filesystem/RegularFile.js";
import type { FileHandle } from "node:fs/promises";
import type { Stats } from "node:fs";
import type { StableRegularFileDescriptor } from "../../filesystem/RegularFile.js";
import type { OwnedFileHandle } from "../../filesystem/OwnedFileHandle.js";
import { classifyArtifactContent } from "./ArtifactGraphConstruction.js";
import { ARTIFACT_CLASSIFICATION_PREFIX_BYTES } from "../ArtifactHash.js";
@@ -12,13 +15,8 @@ import {
zipPackageFormatForPath,
} from "../../domain/zipPackageFormat.js";
import { ArtifactReaderFailure } from "../ArtifactReader.js";
import { type ArtifactResourceOwner } from "../ArtifactResourceScope.js";
import type { HashResult } from "../ArtifactHash.js";
import {
hashStableRootArtifactHandle,
openRootArtifact,
} from "./hashStableRootArtifact.js";
import type { ArtifactInventoryOptions } from "./types.js";
import { hashStableRootArtifactHandle } from "./hashStableRootArtifact.js";
interface RootClassification {
readonly format: ArtifactOccurrence["artifact_format"];
@@ -26,47 +24,27 @@ interface RootClassification {
}
type RootInventoryClassification = RootClassification & {
readonly rootSource: RootInventorySource | undefined;
readonly rootSource: StableRegularFileDescriptor | undefined;
};
/** The admitted descriptor and the single owner that can confirm its close. */
export interface RootInventorySource extends StableRegularFileDescriptor {
readonly owner: OwnedFileHandle;
}
/** Classify and hash one file root through the same stable open descriptor. */
export const classifyAndHashRoot = async (
path: string,
directory: boolean,
expectedMetadata: Stats,
options: Pick<ArtifactInventoryOptions, "resourceScope" | "signal">,
signal?: AbortSignal,
): Promise<RootClassification> => {
return options.resourceScope.run(async () => {
const result = await classifyAndHashRootForInventory(
path,
directory,
expectedMetadata,
options,
);
const rootSource = result.rootSource;
if (rootSource !== undefined) {
const owner: ArtifactResourceOwner = {
kind: "file-handle",
handle: rootSource.owner,
resource: `root artifact descriptor for ${path}`,
};
const cleanupAttempt = await options.resourceScope.release(owner);
if (cleanupAttempt.kind === "failed")
throw ArtifactReaderFailure.withCleanup(
cleanupAttempt.cause,
ArtifactReaderFailure.cleanupObservation(
cleanupAttempt.cause,
owner.resource,
),
);
}
const result = await classifyAndHashRootForInventory(
path,
directory,
expectedMetadata,
signal,
);
try {
return { format: result.format, digest: result.digest };
});
} finally {
await result.rootSource?.handle.close();
}
};
/** Classify a root and retain its admitted ZIP descriptor for child inventory. */
@@ -74,27 +52,12 @@ export const classifyAndHashRootForInventory = async (
path: string,
directory: boolean,
expectedMetadata: Stats,
options: Pick<ArtifactInventoryOptions, "resourceScope" | "signal">,
signal?: AbortSignal,
): Promise<RootInventoryClassification> => {
if (directory)
return { format: "directory", digest: null, rootSource: undefined };
const ownedHandle = await openRootArtifact(
path,
options.resourceScope,
options.signal,
);
const handle = ownedHandle.handle;
const owner: ArtifactResourceOwner = {
kind: "file-handle",
handle: ownedHandle,
resource: `root artifact descriptor for ${path}`,
};
let outcome:
| {
readonly kind: "completed";
readonly value: RootInventoryClassification;
}
| { readonly kind: "failed"; readonly cause: unknown };
const handle = await openRootFile(path, signal);
let transferHandle = false;
try {
const initial = await handle.stat();
if (!sameRegularFileState(expectedMetadata, initial))
@@ -107,35 +70,18 @@ export const classifyAndHashRootForInventory = async (
path,
handle,
initial,
options.signal,
signal,
);
const retainSource = isZipFormat(format) || format === "mach-o-universal";
outcome = {
kind: "completed",
value: {
format,
digest,
rootSource: retainSource
? { handle, initial, owner: ownedHandle }
: undefined,
},
if (retainSource) transferHandle = true;
return {
format,
digest,
rootSource: retainSource ? { handle, initial } : undefined,
};
} catch (cause: unknown) {
outcome = { kind: "failed", cause };
} finally {
if (!transferHandle) await handle.close();
}
if (outcome.kind === "failed" || outcome.value.rootSource === undefined) {
const cleanupAttempt = await options.resourceScope.release(owner);
if (cleanupAttempt.kind === "failed")
throw ArtifactReaderFailure.withCleanup(
outcome.kind === "failed" ? outcome.cause : cleanupAttempt.cause,
ArtifactReaderFailure.cleanupObservation(
cleanupAttempt.cause,
owner.resource,
),
);
}
if (outcome.kind === "failed") throw outcome.cause;
return outcome.value;
};
const isZipFormat = (format: ArtifactOccurrence["artifact_format"]): boolean =>
@@ -145,6 +91,23 @@ const isZipFormat = (format: ArtifactOccurrence["artifact_format"]): boolean =>
format === "msix" ||
format === "appx";
const openRootFile = async (
path: string,
signal?: AbortSignal,
): Promise<FileHandle> => {
try {
return await openRegularFile(path, { symlinks: "reject", signal });
} catch (cause: unknown) {
if (cause instanceof NonRegularFileReadError)
throw new ArtifactReaderFailure(
"format",
`Artifact root is not a regular file: ${path}`,
{ cause },
);
throw cause;
}
};
const classifyRootFormat = async (
path: string,
handle: FileHandle,
@@ -1,13 +1,10 @@
import { lstat } from "node:fs/promises";
import type { Stats } from "node:fs";
import type { FileHandle } from "node:fs/promises";
import { readFileHandleChunks } from "../../filesystem/readFileHandleChunks.js";
import { OwnedFileHandle } from "../../filesystem/OwnedFileHandle.js";
import { ArtifactReaderFailure } from "../ArtifactReader.js";
import {
NonRegularFileReadError,
RegularFileAdmissionFailure,
openRegularFile,
sameRegularFileState,
} from "../../filesystem/RegularFile.js";
@@ -16,79 +13,33 @@ import {
hashReadable,
type HashResult,
} from "../ArtifactHash.js";
import type { ArtifactResourceScope } from "../ArtifactResourceScope.js";
/** Admit a root descriptor without losing ownership when validation cleanup fails. */
export const openRootArtifact = async (
path: string,
resourceScope: ArtifactResourceScope,
signal?: AbortSignal,
): Promise<OwnedFileHandle> => {
try {
return new OwnedFileHandle(
await openRegularFile(path, { symlinks: "reject", signal }),
);
} catch (cause: unknown) {
const primary =
cause instanceof RegularFileAdmissionFailure ? cause.cause : cause;
const failure =
primary instanceof NonRegularFileReadError
? new ArtifactReaderFailure(
"format",
`Artifact root is not a regular file: ${path}`,
{ cause: primary },
)
: primary;
if (cause instanceof RegularFileAdmissionFailure) {
const resource = `root artifact descriptor for ${path}`;
const cleanup = await resourceScope.release({
kind: "file-handle",
resource,
handle: cause.owner,
});
if (cleanup.kind === "failed")
throw ArtifactReaderFailure.withCleanup(
failure,
ArtifactReaderFailure.cleanupObservation(cleanup.cause, resource),
);
}
throw failure;
}
};
/** Hash one stable regular root file from the same descriptor that was checked. */
export const hashStableRootArtifact = async (
path: string,
resourceScope: ArtifactResourceScope,
signal?: AbortSignal,
): Promise<HashResult> => {
const owner = await openRootArtifact(path, resourceScope, signal);
const handle = owner.handle;
let outcome:
| { readonly kind: "completed"; readonly value: HashResult }
| { readonly kind: "failed"; readonly cause: unknown };
let handle: FileHandle;
try {
handle = await openRegularFile(path, {
symlinks: "reject",
signal,
});
} catch (cause: unknown) {
if (cause instanceof NonRegularFileReadError)
throw new ArtifactReaderFailure(
"format",
`Artifact root is not a regular file: ${path}`,
{ cause },
);
throw cause;
}
try {
const initial = await handle.stat();
outcome = {
kind: "completed",
value: await hashStableRootArtifactHandle(path, handle, initial, signal),
};
} catch (cause: unknown) {
outcome = { kind: "failed", cause };
return await hashStableRootArtifactHandle(path, handle, initial, signal);
} finally {
await handle.close();
}
const resource = `root artifact descriptor for ${path}`;
const cleanup = await resourceScope.release({
kind: "file-handle",
resource,
handle: owner,
});
if (cleanup.kind === "failed")
throw ArtifactReaderFailure.withCleanup(
outcome.kind === "failed" ? outcome.cause : cleanup.cause,
ArtifactReaderFailure.cleanupObservation(cleanup.cause, resource),
);
if (outcome.kind === "failed") throw outcome.cause;
return outcome.value;
};
/** Hash and revalidate the same open descriptor used for root classification. */
@@ -101,7 +52,7 @@ export const hashStableRootArtifactHandle = async (
const digest = await hashReadable(
// Read at most the admitted extent plus one byte to detect growth without
// following an actively appended file indefinitely.
readFileHandleChunks(handle, { start: 0, end: initial.size }),
handle.createReadStream({ autoClose: false, start: 0, end: initial.size }),
signal,
);
abortIfNeeded(signal);
+4 -3
View File
@@ -8,12 +8,13 @@ import type { ArtifactOccurrence } from "../../domain/artifactGraph.js";
import { ZIP_NON_ENTRY_TAIL_LIMITATION } from "../../domain/zipPackageFormat.js";
import type { StableRegularFileDescriptor } from "../../filesystem/RegularFile.js";
export const createReader = (
export const createReader = async (
path: string,
format: ArtifactOccurrence["artifact_format"],
environment: Readonly<NodeJS.ProcessEnv>,
signal?: AbortSignal,
rootSource?: StableRegularFileDescriptor,
): ArtifactReader | undefined => {
): Promise<ArtifactReader | undefined> => {
switch (format) {
case "directory":
return new DirectoryArtifactReader(path);
@@ -31,7 +32,7 @@ export const createReader = (
: undefined;
case "dmg":
if (process.platform !== "darwin") return undefined;
return new NativeDmgArtifactReader(path, environment);
return NativeDmgArtifactReader.create(path, environment, signal);
default:
return undefined;
}
+52 -86
View File
@@ -5,13 +5,12 @@ import { AsarArtifactReader } from "../AsarArtifactReader.js";
import { lstat } from "node:fs/promises";
import type { Stats } from "node:fs";
import type { RootInventorySource } from "./classify.js";
import type { StableRegularFileDescriptor } from "../../filesystem/RegularFile.js";
import {
ArtifactReaderFailure,
type ArtifactReader,
} from "../ArtifactReader.js";
import type { ArtifactResourceOwner } from "../ArtifactResourceScope.js";
import {
artifactInventoryResultSchema,
type ArtifactInventoryResult,
@@ -51,16 +50,7 @@ import {
export const scanCanonicalArtifactInventory = async (
path: string,
options: ArtifactInventoryOptions,
readerFactory: typeof createReader = createReader,
): Promise<ArtifactInventorySnapshot> =>
options.resourceScope.run(() =>
scanCanonicalArtifactInventoryInScope(path, options, readerFactory),
);
export const scanCanonicalArtifactInventoryInScope = async (
path: string,
options: ArtifactInventoryOptions,
options: ArtifactInventoryOptions = {},
readerFactory: typeof createReader = createReader,
): Promise<ArtifactInventorySnapshot> => {
const integrity = options.integrity ?? STRICT_INTEGRITY_POLICY;
@@ -73,22 +63,28 @@ export const scanCanonicalArtifactInventoryInScope = async (
path,
metadata.isDirectory(),
metadata,
options,
options.signal,
);
let reader: ArtifactReader | undefined;
let readerCreationFailure: { readonly cause: unknown } | undefined;
try {
reader = readerFactory(
reader = await readerFactory(
path,
rootFormat,
options.environment ?? {},
options.signal,
rootSource,
);
} catch (cause: unknown) {
readerCreationFailure = { cause };
}
const ownedReaders: ArtifactReader[] = reader === undefined ? [] : [reader];
let outcome: InventoryScanOutcome;
let outcome:
| {
readonly kind: "completed";
readonly snapshot: ArtifactInventorySnapshot;
}
| { readonly kind: "failed"; readonly cause: unknown };
try {
if (readerCreationFailure !== undefined) throw readerCreationFailure.cause;
if (reader instanceof AsarArtifactReader)
@@ -107,7 +103,6 @@ export const scanCanonicalArtifactInventoryInScope = async (
rootFormat,
rootDigest,
rootSource,
resourceScope: options.resourceScope,
reader,
signal: options.signal,
nodes,
@@ -119,76 +114,54 @@ export const scanCanonicalArtifactInventoryInScope = async (
} catch (cause: unknown) {
outcome = { kind: "failed", cause };
}
const cleanupFailure = await cleanupInventoryOwners({
path,
options,
rootSource,
ownedReaders,
outcome,
});
let cleanupFailure: ArtifactReaderFailure | undefined;
for (const owned of ownedReaders.reverse()) {
try {
await owned.close();
} catch (cleanupCause: unknown) {
const cleanup = ArtifactReaderFailure.cleanupObservation(
cleanupCause,
`artifact reader for ${path}`,
);
cleanupFailure = ArtifactReaderFailure.withCleanup(
cleanupFailure ??
(outcome.kind === "failed" ? outcome.cause : cleanupCause),
cleanup,
outcome.kind === "completed"
? { kind: "artifact-inventory", inventory: outcome.snapshot }
: undefined,
);
}
}
if (rootSource !== undefined) {
try {
await rootSource.handle.close();
} catch (cleanupCause: unknown) {
const cleanup = ArtifactReaderFailure.cleanupObservation(
cleanupCause,
`root artifact descriptor for ${path}`,
);
cleanupFailure = ArtifactReaderFailure.withCleanup(
cleanupFailure ??
(outcome.kind === "failed" ? outcome.cause : cleanupCause),
cleanup,
outcome.kind === "completed"
? { kind: "artifact-inventory", inventory: outcome.snapshot }
: undefined,
);
}
}
if (cleanupFailure !== undefined) throw cleanupFailure;
if (outcome.kind === "failed") throw outcome.cause;
return outcome.snapshot;
};
type InventoryScanOutcome =
| {
readonly kind: "completed";
readonly snapshot: ArtifactInventorySnapshot;
}
| { readonly kind: "failed"; readonly cause: unknown };
const cleanupInventoryOwners = async ({
path,
options,
rootSource,
ownedReaders,
outcome,
}: {
readonly path: string;
readonly options: ArtifactInventoryOptions;
readonly rootSource: RootInventorySource | undefined;
readonly ownedReaders: readonly ArtifactReader[];
readonly outcome: InventoryScanOutcome;
}): Promise<ArtifactReaderFailure | undefined> => {
let cleanupFailure: ArtifactReaderFailure | undefined;
const owners: ArtifactResourceOwner[] = [...ownedReaders]
.reverse()
.map((reader) => ({
kind: "reader" as const,
reader,
resource: `artifact reader for ${path}`,
}));
if (rootSource !== undefined)
owners.push({
kind: "file-handle",
handle: rootSource.owner,
resource: `root artifact descriptor for ${path}`,
});
for (const owner of owners) {
const attempt = await options.resourceScope.release(owner);
if (attempt.kind === "released") continue;
const primary =
cleanupFailure ??
(outcome.kind === "failed" ? outcome.cause : attempt.cause);
cleanupFailure = ArtifactReaderFailure.withCleanup(
primary,
ArtifactReaderFailure.cleanupObservation(attempt.cause, owner.resource),
outcome.kind === "completed"
? { kind: "artifact-inventory", inventory: outcome.snapshot }
: undefined,
);
}
return cleanupFailure;
};
interface SnapshotBuildInput {
readonly resourceScope: ArtifactInventoryOptions["resourceScope"];
readonly path: string;
readonly metadata: Stats;
readonly rootFormat: ArtifactOccurrence["artifact_format"];
readonly rootDigest: HashResult | null;
readonly rootSource: RootInventorySource | undefined;
readonly rootSource: StableRegularFileDescriptor | undefined;
readonly reader: ArtifactReader | undefined;
readonly signal: AbortSignal | undefined;
readonly nodes: Map<string, ArtifactNode>;
@@ -245,13 +218,7 @@ const buildInventorySnapshot = async (
ordinal,
}));
await verifyRootDigest(
path,
rootDigest,
rootSource,
input.resourceScope,
signal,
);
await verifyRootDigest(path, rootDigest, rootSource, signal);
const graphSha256 = artifactGraphDigest({
nodes: orderedNodes,
@@ -326,14 +293,13 @@ const buildIntegrityContradictions = (
const verifyRootDigest = async (
path: string,
rootDigest: HashResult | null,
rootSource: RootInventorySource | undefined,
resourceScope: ArtifactInventoryOptions["resourceScope"],
rootSource: StableRegularFileDescriptor | undefined,
signal: AbortSignal | undefined,
): Promise<void> => {
if (rootDigest === null) return;
const verified =
rootSource === undefined
? await hashStableRootArtifact(path, resourceScope, signal)
? await hashStableRootArtifact(path, signal)
: await hashStableRootArtifactHandle(
path,
rootSource.handle,
+1 -19
View File
@@ -120,7 +120,6 @@ const visitArtifactEntries = async (
iterator: currentReader.entries(context.signal)[Symbol.asyncIterator](),
},
];
let failure: { readonly cause: unknown } | undefined;
try {
while (stack.length > 0) {
const frame = stack.at(-1);
@@ -195,27 +194,10 @@ const visitArtifactEntries = async (
});
}
}
} catch (cause: unknown) {
failure = { cause };
} finally {
// Readers remain owned by the inventory until its complete observation is built.
for (const { iterator, prefix, reader } of stack.reverse()) {
try {
await iterator.return?.();
} catch (cause: unknown) {
failure = {
cause: ArtifactReaderFailure.withCleanup(
failure === undefined ? cause : failure.cause,
ArtifactReaderFailure.cleanupObservation(
cause,
`artifact traversal for ${prefix || reader.format}`,
),
),
};
}
}
for (const { iterator } of stack) await iterator.return?.();
}
if (failure !== undefined) throw failure.cause;
};
const digestArtifactEntry = async (
-3
View File
@@ -1,5 +1,3 @@
import type { ArtifactResourceScope } from "../ArtifactResourceScope.js";
/** Resolved integrity behavior admitted to the artifact scanner. */
export type ArtifactIntegrityPolicy =
| { readonly mode: "fail" }
@@ -11,7 +9,6 @@ export const STRICT_INTEGRITY_POLICY: ArtifactIntegrityPolicy = {
/** Options shared by artifact inventory scans. */
export interface ArtifactInventoryOptions {
readonly resourceScope: ArtifactResourceScope;
readonly signal?: AbortSignal | undefined;
readonly integrity?: ArtifactIntegrityPolicy | undefined;
readonly environment?: Readonly<NodeJS.ProcessEnv> | undefined;
@@ -4,7 +4,6 @@ import type { Readable } from "node:stream";
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
import { AsarArtifactReader } from "../AsarArtifactReader.js";
import type { ArtifactResourceScope } from "../ArtifactResourceScope.js";
import {
ArtifactPathRegistry,
normalizeArtifactPath,
@@ -40,7 +39,6 @@ interface ExpectedContainer {
}
interface ReadContext {
readonly resources: ArtifactResourceScope;
readonly expected: ReadonlyMap<string, ExpectedFile>;
readonly expectedContainers: ReadonlyMap<string, ExpectedContainer>;
readonly registry: ArtifactPathRegistry;
@@ -61,7 +59,6 @@ interface ReadTextInput {
export const readJavaScriptArtifactFiles = async (
reader: ArtifactReader,
snapshot: ArtifactInventorySnapshot,
resources: ArtifactResourceScope,
signal?: AbortSignal,
): Promise<JavaScriptArtifactFileSet> => {
if (reader instanceof AsarArtifactReader) {
@@ -82,7 +79,6 @@ export const readJavaScriptArtifactFiles = async (
const inventory = expectedInventory(snapshot);
const expected = inventory.files;
const context: ReadContext = {
resources,
expected,
expectedContainers: inventory.containers,
registry: new ArtifactPathRegistry(),
@@ -126,10 +122,7 @@ const visitReader = async (
iterator: reader.entries(context.signal)[Symbol.asyncIterator](),
},
];
const ownedReaders: {
readonly reader: ArtifactReader;
readonly path: string;
}[] = [];
const ownedReaders: ArtifactReader[] = [];
let failure: { readonly cause: unknown } | undefined;
try {
while (stack.length > 0) {
@@ -181,7 +174,7 @@ const visitReader = async (
);
context.containers.push(inventory);
const nested = new AsarArtifactReader(entry.adapterKey);
ownedReaders.push({ reader: nested, path });
ownedReaders.push(nested);
stack.push({
reader: nested,
prefix: path,
@@ -212,33 +205,24 @@ const visitReader = async (
} catch (cause: unknown) {
failure = { cause };
} finally {
for (const { iterator, prefix, reader } of stack.reverse()) {
for (const { iterator } of stack) {
try {
await iterator.return?.();
} catch (cause: unknown) {
failure = {
cause: ArtifactReaderFailure.withCleanup(
failure === undefined ? cause : failure.cause,
ArtifactReaderFailure.cleanupObservation(
cause,
`JavaScript artifact traversal for ${prefix || reader.format}`,
),
),
};
failure ??= { cause };
}
}
for (const owned of ownedReaders.reverse()) {
const resource = `nested ASAR reader for ${owned.path}`;
const cleanup = await context.resources.release({
kind: "reader",
reader: owned.reader,
resource,
});
if (cleanup.kind === "failed") {
try {
await owned.close();
} catch (cause: unknown) {
failure = {
cause: ArtifactReaderFailure.withCleanup(
failure === undefined ? cleanup.cause : failure.cause,
ArtifactReaderFailure.cleanupObservation(cleanup.cause, resource),
failure?.cause ?? cause,
ArtifactReaderFailure.cleanupObservation(
cause,
`nested ASAR reader for ${prefix}`,
),
),
};
}
@@ -1,12 +0,0 @@
import type {
JavaScriptSourceAnalysisLimits,
JavaScriptSourceAnalysisPort,
} from "../../domain/javascript/javascriptSourceAnalysis.js";
import { JavaScriptAnalysisWorker } from "../../javascript/analysis/JavaScriptAnalysisWorker.js";
/** Construct the inert artifact analyzer; resources are acquired on the first source. */
export const createJavaScriptSourceAnalysis = (
limits: JavaScriptSourceAnalysisLimits,
sourceCount: number,
): JavaScriptSourceAnalysisPort =>
new JavaScriptAnalysisWorker(limits, undefined, sourceCount);
-47
View File
@@ -147,53 +147,6 @@ describe("browserScenarioSchema", () => {
expect(secrets?.redact("prefix-suffix")).toBe("[REDACTED:login_input]");
});
it("does not leave a declared secret inside its redaction marker", () => {
const secrets = BrowserScenarioSecrets.resolve(
browserScenarioSchema.parse({
...baseScenario(),
secrets: [
...baseScenario().secrets,
{
secret_id: "password",
environment_variable: "REA_TEST_SHORT_PASSWORD",
},
],
}),
{
REA_TEST_SESSION: "prefix",
REA_TEST_PASSWORD: "prefix-suffix",
REA_TEST_COOKIE: "cookie",
REA_TEST_SHORT_PASSWORD: "pass",
},
);
expect(secrets?.redact("seen pass in the page")).toBe(
"seen [REDACTED] in the page",
);
const bytes = BrowserScenarioSecrets.resolve(
browserScenarioSchema.parse({
...baseScenario(),
secrets: [
...baseScenario().secrets,
{
secret_id: "password",
environment_variable: "REA_TEST_LONG_SECRET",
},
{ secret_id: "pin", environment_variable: "REA_TEST_PIN" },
],
}),
{
REA_TEST_SESSION: "prefix",
REA_TEST_PASSWORD: "prefix-suffix",
REA_TEST_COOKIE: "cookie",
REA_TEST_LONG_SECRET: "session-secret-value",
REA_TEST_PIN: "pass",
},
)?.redactBytes(Buffer.from("body session-secret-value tail"));
expect(bytes?.toString("utf8")).toBe("body [REDACTED] tail");
expect(bytes?.includes(Buffer.from("pass"))).toBe(false);
});
it("does not resolve inherited environment properties as secret values", () => {
const scenario = browserScenarioSchema.parse(baseScenario());
const environment = Object.assign(
+41 -92
View File
@@ -20,76 +20,6 @@ const encodedSecretValues = (secret: string): ReadonlySet<string> =>
new URLSearchParams([["value", secret]]).toString().slice("value=".length),
]);
type SecretSpellings = "raw" | "url" | "bytes";
const secretSpellings = (
secret: string,
spellings: SecretSpellings,
): readonly string[] => {
if (secret === "") return [];
if (spellings === "raw") return [secret];
const values = [...encodedSecretValues(secret)];
if (spellings === "bytes") values.push(JSON.stringify(secret).slice(1, -1));
return [...new Set(values)].filter((value) => value !== "");
};
const declaredLiterals = (
values: ReadonlyMap<string, string>,
spellings: SecretSpellings,
): readonly string[] => [
...new Set(
[...values.values()].flatMap((secret) =>
secretSpellings(secret, spellings),
),
),
];
/** Pick a marker that does not itself contain a declared secret spelling. */
const redactionMarker = (id: string, literals: readonly string[]): string =>
[`${REDACTION_PREFIX}${id}]`, "[REDACTED]", "…", ""].find((candidate) =>
literals.every((literal) => !candidate.includes(literal)),
) ?? "";
const replaceSecretLiterals = (
value: string,
values: ReadonlyMap<string, string>,
spellings: SecretSpellings,
literals: readonly string[],
): string => {
const replacements = [...values]
.flatMap(([id, secret]) =>
secretSpellings(secret, spellings).map((text) => ({ id, text })),
)
.sort(
(left, right) =>
right.text.length - left.text.length ||
(left.id < right.id ? -1 : left.id > right.id ? 1 : 0),
);
let output = value;
for (const replacement of replacements)
output = output.replaceAll(
replacement.text,
redactionMarker(replacement.id, literals),
);
return output;
};
const secretNeedles = (
values: ReadonlyMap<string, string>,
literals: readonly string[],
): Array<{
readonly id: string;
readonly needle: Buffer;
readonly marker: Buffer;
}> =>
[...values].flatMap(([id, secret]) =>
secretSpellings(secret, "bytes").map((text) => ({
id,
needle: Buffer.from(text),
marker: Buffer.from(redactionMarker(id, literals)),
})),
);
/** Resolved secret values kept only for one in-memory scenario session. */
export class BrowserScenarioSecrets {
private constructor(private readonly values: ReadonlyMap<string, string>) {}
@@ -127,19 +57,38 @@ export class BrowserScenarioSecrets {
}
redact(value: string): string {
const literals = declaredLiterals(this.values, "raw");
const output = replaceSecretLiterals(value, this.values, "raw", literals);
return literals.some((literal) => output.includes(literal)) ? "" : output;
let output = value;
const replacements = [...this.values].sort(
([leftId, left], [rightId, right]) =>
right.length - left.length ||
(leftId < rightId ? -1 : leftId > rightId ? 1 : 0),
);
for (const [id, secret] of replacements)
if (secret !== "")
output = output.replaceAll(secret, `${REDACTION_PREFIX}${id}]`);
return output;
}
/** Replace declared UTF-8, URI/form, and JSON-escaped secrets without decoding binary data. */
redactBytes(value: Buffer): Buffer {
const literals = declaredLiterals(this.values, "bytes");
const candidates = secretNeedles(this.values, literals)
.map((candidate) => ({
...candidate,
index: value.indexOf(candidate.needle),
}))
const candidates = [...this.values]
.flatMap(([id, secret]) => {
if (secret === "") return [];
return [
...new Set([
...encodedSecretValues(secret),
JSON.stringify(secret).slice(1, -1),
]),
].map((text) => {
const needle = Buffer.from(text);
return {
id,
needle,
marker: Buffer.from(`${REDACTION_PREFIX}${id}]`),
index: value.indexOf(needle),
};
});
})
.sort(
(left, right) =>
right.needle.length - left.needle.length ||
@@ -164,23 +113,23 @@ export class BrowserScenarioSecrets {
}
if (parts.length === 0) return value;
parts.push(value.subarray(offset));
const redacted = Buffer.concat(parts);
return literals.some((literal) => redacted.includes(Buffer.from(literal)))
? Buffer.alloc(0)
: redacted;
return Buffer.concat(parts);
}
/** Remove only declared secret values from one URL and report that action. */
sanitizeUrl(value: string): SanitizedBrowserUrl {
const literals = declaredLiterals(this.values, "url");
const output = replaceSecretLiterals(value, this.values, "url", literals);
if (literals.some((literal) => output.includes(literal)))
return {
url: "",
origin: null,
query_parameter_names: [],
redacted: true,
};
let output = value;
const replacements = [...this.values].sort(
([leftId, left], [rightId, right]) =>
right.length - left.length ||
(leftId < rightId ? -1 : leftId > rightId ? 1 : 0),
);
for (const [id, secret] of replacements) {
if (secret === "") continue;
const marker = `${REDACTION_PREFIX}${id}]`;
for (const candidate of encodedSecretValues(secret))
output = output.replaceAll(candidate, marker);
}
const sanitized = sanitizeBrowserUrl(output);
return {
...sanitized,
@@ -277,332 +277,3 @@ it("preserves case-sensitive SVG attributes and uses the actual href", () => {
`${origin}/actual`,
);
});
interface SvgSnapshotNode {
readonly name: string;
readonly parent: number;
readonly attributes?: readonly (readonly [string, string])[];
}
const svgDocument = (
elements: readonly SvgSnapshotNode[],
baseUrl = `${origin}/screens/assets/`,
) => {
const strings = [documentUrl, baseUrl];
const intern = (value: string): number => {
const existing = strings.indexOf(value);
if (existing >= 0) return existing;
strings.push(value);
return strings.length - 1;
};
const nodeType = [9];
const nodeName = [intern("#document")];
const nodeValue = [intern("")];
const parentIndex = [-1];
const attributes: number[][] = [[]];
for (const element of elements) {
nodeType.push(1);
nodeName.push(intern(element.name));
nodeValue.push(intern(""));
parentIndex.push(element.parent);
const encoded: number[] = [];
for (const [name, value] of element.attributes ?? [])
encoded.push(intern(name), intern(value));
attributes.push(encoded);
}
return {
strings,
documents: [
{
documentURL: 0,
baseURL: 1,
nodes: { nodeType, nodeName, nodeValue, parentIndex, attributes },
},
],
};
};
const captureSvg = (value: ReturnType<typeof svgDocument>) =>
captureDom(value, new Set([origin]), input);
const urlFor = (
result: ReturnType<typeof captureSvg>,
nodeIndex: number,
): (typeof result.urls)[number] | undefined =>
result.urls.find((url) => url.node_index === nodeIndex);
describe("SVG xlink:href destinations", () => {
it("reports an SVG anchor that only has xlink:href, keeping the first value", () => {
const result = captureSvg(
svgDocument([
{ name: "svg", parent: 0 },
{ name: "g", parent: 1 },
{
name: "a",
parent: 2,
attributes: [
["xlink:href", "/xl-s2h"],
["xlink:href", "/later"],
],
},
]),
);
expect(result.nodes[3]?.attribute_names).toEqual(["xlink:href"]);
expect(result.urls).toEqual([
{
node_index: 3,
attribute: "href",
url: `${origin}/xl-s2h`,
destination_scope: "approved",
},
]);
});
it.each([
["xlink:href", "href"],
["href", "xlink:href"],
] as const)(
"uses href when an SVG anchor also has xlink:href (%s then %s)",
(first, second) => {
const valueFor = (name: string): string =>
name === "href" ? "/href-wins" : "/xlink-loses";
const result = captureSvg(
svgDocument([
{ name: "svg", parent: 0 },
{
name: "a",
parent: 1,
attributes: [
[first, valueFor(first)],
[second, valueFor(second)],
],
},
]),
);
expect(result.urls).toEqual([
{
node_index: 2,
attribute: "href",
url: `${origin}/href-wins`,
destination_scope: "approved",
},
]);
},
);
it("does not report xlink:href on an HTML anchor or a MathML element", () => {
const result = captureSvg(
svgDocument([
{
name: "A",
parent: 0,
attributes: [["xlink:href", "/xl-html"]],
},
{ name: "math", parent: 0 },
{
name: "mrow",
parent: 2,
attributes: [["xlink:href", "/xl-math"]],
},
{ name: "svg", parent: 0 },
{
name: "a",
parent: 4,
attributes: [["xlink:href", "/xl-s2h"]],
},
]),
);
expect(result.nodes[1]?.attribute_names).toEqual(["xlink:href"]);
expect(result.nodes[3]?.attribute_names).toEqual(["xlink:href"]);
expect(urlFor(result, 1)).toBeUndefined();
expect(urlFor(result, 3)).toBeUndefined();
expect(urlFor(result, 5)?.url).toBe(`${origin}/xl-s2h`);
});
it("classifies an SVG xlink:href outside the allowed origins as outside_policy", () => {
const result = captureSvg(
svgDocument([
{ name: "svg", parent: 0 },
{
name: "a",
parent: 1,
attributes: [["xlink:href", "https://cdn.example.test/out"]],
},
]),
);
expect(result.urls).toEqual([
{
node_index: 2,
attribute: "href",
url: null,
destination_scope: "outside_policy",
},
]);
});
it("resolves SVG image and use xlink:href against the document base", () => {
const result = captureSvg(
svgDocument([
{ name: "svg", parent: 0 },
{ name: "image", parent: 1, attributes: [["xlink:href", "guide"]] },
{ name: "use", parent: 1, attributes: [["xlink:href", "icon.svg"]] },
]),
);
expect(result.urls).toEqual([
{
node_index: 2,
attribute: "href",
url: `${origin}/screens/assets/guide`,
destination_scope: "approved",
},
{
node_index: 3,
attribute: "href",
url: `${origin}/screens/assets/icon.svg`,
destination_scope: "approved",
},
]);
});
});
describe("SVG xlink:href context", () => {
it("keeps forward ancestor context local to each document", () => {
const svg = svgDocument([
{ name: "a", parent: 2, attributes: [["xlink:href", "/svg-link"]] },
{ name: "g", parent: 3 },
{ name: "svg", parent: 0 },
]);
const html = svgDocument([
{ name: "A", parent: 2, attributes: [["xlink:href", "/html-link"]] },
{ name: "DIV", parent: 3 },
{ name: "BODY", parent: 0 },
]);
const offset = svg.strings.length;
const result = captureSvg({
strings: [...svg.strings, ...html.strings],
documents: [
...svg.documents,
...html.documents.map((document) => ({
...document,
documentURL: document.documentURL + offset,
baseURL: document.baseURL + offset,
nodes: {
...document.nodes,
nodeName: document.nodes.nodeName.map((index) => index + offset),
nodeValue: document.nodes.nodeValue.map((index) => index + offset),
attributes: document.nodes.attributes.map((attributes) =>
attributes.map((index) => index + offset),
),
},
})),
],
});
expect(result.urls).toEqual([
{
node_index: 1,
attribute: "href",
url: `${origin}/svg-link`,
destination_scope: "approved",
},
]);
});
it("stops SVG context at foreignObject and resumes it for a nested svg", () => {
const result = captureSvg(
svgDocument([
{ name: "svg", parent: 0 },
{ name: "foreignObject", parent: 1 },
{
name: "A",
parent: 2,
attributes: [["xlink:href", "/xl-html-fo"]],
},
{ name: "svg", parent: 2 },
{
name: "a",
parent: 4,
attributes: [["xlink:href", "/xl-nested"]],
},
]),
);
expect(urlFor(result, 3)).toBeUndefined();
expect(urlFor(result, 5)).toMatchObject({
attribute: "href",
url: `${origin}/xl-nested`,
destination_scope: "approved",
});
});
it("keeps an empty href ahead of xlink:href", () => {
const baseUrl = `${origin}/screens/assets/`;
const result = captureSvg(
svgDocument(
[
{ name: "svg", parent: 0 },
{
name: "a",
parent: 1,
attributes: [
["href", ""],
["xlink:href", "/xlink-should-lose"],
],
},
],
baseUrl,
),
);
expect(result.urls).toEqual([
{
node_index: 2,
attribute: "href",
url: baseUrl,
destination_scope: "approved",
},
]);
});
it("classifies a non-http SVG xlink:href as unsupported", () => {
const result = captureSvg(
svgDocument([
{ name: "svg", parent: 0 },
{
name: "a",
parent: 1,
attributes: [["xlink:href", "javascript:void(0)"]],
},
]),
);
expect(result.urls).toEqual([
{
node_index: 2,
attribute: "href",
url: null,
destination_scope: "unsupported",
},
]);
});
it("does not treat a cyclic or dangling parent chain as SVG", () => {
const cyclic = captureSvg(
svgDocument([
{ name: "g", parent: 2 },
{
name: "a",
parent: 1,
attributes: [["xlink:href", "/cycle"]],
},
]),
);
const dangling = captureSvg(
svgDocument([
{
name: "a",
parent: 99,
attributes: [["xlink:href", "/missing-parent"]],
},
]),
);
expect(cyclic.urls).toEqual([]);
expect(dangling.urls).toEqual([]);
});
});
+1 -52
View File
@@ -171,7 +171,6 @@ export const captureDom = (
? documentNodes.attributes
: [];
const baseIndex = nodes.length;
const svgContexts = new Map<number, boolean>();
total += nodeTypes.length;
for (let index = 0; index < nodeTypes.length; index += 1) {
const attributeIndexes = numberArray(attributes[index]);
@@ -206,13 +205,6 @@ export const captureDom = (
nodeIndex,
nodeName,
allowedOrigins,
svgElement: elementInSvgContext(
index,
nodeNames,
parents,
strings,
svgContexts,
),
});
for (const url of metadata.urls) {
urls.push(url);
@@ -383,44 +375,8 @@ interface DomMetadataOptions {
readonly nodeIndex: number;
readonly nodeName: string;
readonly allowedOrigins: ReadonlySet<string>;
readonly svgElement: boolean;
}
// DOMSnapshot carries no namespace URI. Chrome's HTML parser records SVG
// local names (`svg`, `foreignObject`). Descendants of foreignObject are HTML
// until a nested `svg`.
const elementInSvgContext = (
index: number,
nodeNames: readonly number[],
parents: readonly number[],
strings: readonly string[],
contexts: Map<number, boolean>,
): boolean => {
let current = index;
const seen = new Set<number>();
let inSvg = false;
while (current >= 0 && current < nodeNames.length && !seen.has(current)) {
const cached = contexts.get(current);
if (cached !== undefined) {
inSvg = cached;
break;
}
seen.add(current);
if (indexedString(strings, nodeNames[current]) === "svg") {
inSvg = true;
break;
}
const parent = Math.trunc(parents[current] ?? -1);
if (parent < 0 || parent === current) break;
if (indexedString(strings, nodeNames[parent]) === "foreignObject") break;
current = parent;
}
// Cache the entire examined chain, including forward references and cycles,
// so shared ancestors are examined once per document.
for (const node of seen) contexts.set(node, inSvg);
return inSvg;
};
const domMetadata = (
options: DomMetadataOptions,
): {
@@ -435,7 +391,6 @@ const domMetadata = (
nodeIndex,
nodeName,
allowedOrigins,
svgElement,
} = options;
const pairs = new Map<string, string>();
for (let index = 0; index + 1 < attributes.length; index += 2) {
@@ -447,13 +402,7 @@ const domMetadata = (
}
const urls: WebPageInspection["metadata"]["dom_urls"] = [];
for (const attribute of domUrlAttributes) {
// Chrome reads SVG xlink:href only when href itself is absent, and an
// empty href still wins. Report the fallback as href.
const value =
pairs.get(attribute) ??
(attribute === "href" && svgElement
? pairs.get("xlink:href")
: undefined);
const value = pairs.get(attribute);
if (value === undefined) continue;
const tagName = nodeName.toLowerCase();
// Chrome strips HTML whitespace for FORM.action, while submit controls
@@ -1,18 +1,9 @@
import { afterEach, expect, it, vi } from "vitest";
import * as processOwnership from "../process/ProcessOwnership.js";
import * as electronActions from "./PlaywrightElectronActiveActions.js";
import { electronActiveObservationInputSchema } from "../domain/javascript/electronActiveObservation.js";
import type { OwnedProcessGroup } from "../process/ProcessOwnership.js";
import {
cleanupElectronProcesses,
PlaywrightElectronActiveProvider,
} from "./PlaywrightElectronActiveProvider.js";
import { PlaywrightElectronActiveProvider } from "./PlaywrightElectronActiveProvider.js";
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllEnvs();
});
afterEach(() => vi.unstubAllEnvs());
it("passes the selected environment and ownership token to Electron launch", async () => {
vi.stubEnv("LANG", "ambient-language");
@@ -42,143 +33,3 @@ it("passes the selected environment and ownership token to Electron launch", asy
REA_PROCESS_RUN_ID: expect.any(String),
});
});
const ownership = {
runId: "run",
leaderPid: 4242,
processGroupId: 4242,
expectedParentPid: 1,
} satisfies OwnedProcessGroup;
it("does not signal a Windows Electron PID when lineage is unavailable", async () => {
const terminateTree = vi.fn(async () => ({
cleaned: true as const,
signaled: true,
}));
const result = await cleanupElectronProcesses(
ownership,
{
status: "unavailable",
observedAt: "2026-10-10T00:00:00.000Z",
runId: ownership.runId,
launcherPid: ownership.leaderPid,
processGroupId: ownership.processGroupId,
reason: "owned launcher is not live",
},
{ platform: "win32", terminateTree },
);
expect(terminateTree).not.toHaveBeenCalled();
expect(result).toEqual({
cleaned: false,
reason:
"owned Electron lineage was unavailable; helper cleanup was not proven",
});
});
it("signals a Windows Electron tree only after lineage is verified", async () => {
const terminateTree = vi.fn(async () => ({
cleaned: true as const,
signaled: true,
}));
const result = await cleanupElectronProcesses(
ownership,
{
status: "verified",
observedAt: "2026-10-10T00:00:00.000Z",
lineage: {
runId: ownership.runId,
launcherPid: ownership.leaderPid,
launcherParentPid: 1,
processGroupId: ownership.processGroupId,
descendants: [
{
pid: 4343,
parentPid: ownership.leaderPid,
processGroupId: ownership.processGroupId,
},
],
},
},
{ platform: "win32", terminateTree },
);
expect(terminateTree).toHaveBeenNthCalledWith(1, 4242);
expect(terminateTree).toHaveBeenNthCalledWith(2, 4343);
expect(result).toEqual({ cleaned: true, signaled: true });
});
it("retains the partial capture without taskkill when Windows lineage is unavailable", async () => {
// Exercise the Windows decision branch; this is not native Windows coverage.
const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform");
Object.defineProperty(process, "platform", { value: "win32" });
const terminateTree = vi
.spyOn(processOwnership, "cleanupWindowsProcessTree")
.mockResolvedValue({ cleaned: true, signaled: true });
const hookSnapshot = {
events: [],
retention_budget_bytes: 0,
estimated_retained_bytes: 0,
event_serialized_byte_upper_bound: 0,
retained: 0,
dropped: 0,
dropped_ipc: 0,
dropped_runtime: 0,
dropped_event_families: [],
dropped_event_roles: [],
observed: 0,
observed_ipc: 0,
observed_runtime: 0,
hook_error: false,
};
vi.spyOn(electronActions, "readApplicationState").mockResolvedValue({
windows: [],
metrics: [],
electronVersion: "44.0.0",
hookSnapshot,
});
const application = {
process: () => ({ pid: 424242 }),
close: vi.fn(async () => undefined),
windows: () => [],
};
const provider = new PlaywrightElectronActiveProvider(
{},
async () =>
application as unknown as Awaited<
ReturnType<typeof import("playwright-core")._electron.launch>
>,
);
try {
const result = await provider.capture(
electronActiveObservationInputSchema.parse({
executable_path: process.execPath,
application_path: process.execPath,
}),
);
expect(result.ok).toBe(false);
if (result.ok) throw new Error("Expected unverified cleanup to fail");
expect(terminateTree).not.toHaveBeenCalled();
expect(result.error).toMatchObject({
_tag: "BrowserObservationError",
reason: "cleanup_failed",
cleanup: {
reason:
"owned Electron lineage was unavailable; helper cleanup was not proven",
},
partialObservation: {
kind: "electron-active-observation",
capture: {
application: {
cleanup: "unverified",
},
},
},
});
} finally {
if (originalPlatform !== undefined)
Object.defineProperty(process, "platform", originalPlatform);
}
});
@@ -259,30 +259,21 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
}
}
/** Clean up an Electron launch. Windows signals a process only after lineage is verified. */
export const cleanupElectronProcesses = async (
const cleanupElectronProcesses = async (
ownership: OwnedProcessGroup,
lineage: ProcessLineageObservation | undefined,
host: {
readonly platform: NodeJS.Platform;
readonly terminateTree: typeof cleanupWindowsProcessTree;
} = {
platform: process.platform,
terminateTree: cleanupWindowsProcessTree,
},
): Promise<ProcessCleanupResult> => {
if (host.platform === "win32") {
// An empty Windows process table is not ownership proof for this PID.
if (process.platform === "win32") {
const root = await cleanupWindowsProcessTree(ownership.leaderPid);
if (!root.cleaned) return root;
if (lineage?.status !== "verified")
return {
cleaned: false,
reason:
"owned Electron lineage was unavailable; helper cleanup was not proven",
};
const root = await host.terminateTree(ownership.leaderPid);
if (!root.cleaned) return root;
for (const descendant of lineage.lineage.descendants) {
const result = await host.terminateTree(descendant.pid);
const result = await cleanupWindowsProcessTree(descendant.pid);
if (!result.cleaned) return result;
}
return root;
@@ -110,61 +110,3 @@ it("redacts declared secrets from current and historical URL artifacts", async (
},
});
});
it("redacts a declared secret used as a cookie or storage name", async () => {
const secretValue = "session-token";
const scenarioWithSecret = browserScenarioSchema.parse({
browser: { mode: "launch", executable_path: "/opt/chromium" },
start_url: { url: "https://app.example.test/" },
actions: [{ step_id: "wait", action: "wait_for_timeout", duration_ms: 1 }],
secrets: [
{ secret_id: "storage_key", environment_variable: "REA_STORAGE_KEY" },
],
});
const scenarioSecrets = BrowserScenarioSecrets.resolve(scenarioWithSecret, {
REA_STORAGE_KEY: secretValue,
});
if (scenarioSecrets === undefined)
throw new Error("Expected resolved storage secret");
const page = {
url: () => "https://app.example.test/",
evaluate: async () => ({
local_storage: [[secretValue, "kept-value"]],
session_storage: [["theme", secretValue]],
}),
} as unknown as Page;
const context = {
cookies: async () => [
{
name: secretValue,
value: "ordinary",
domain: "app.example.test",
path: "/",
secure: true,
httpOnly: false,
sameSite: "Lax" as const,
},
],
} as unknown as BrowserContext;
const result = await capturePlaywrightStepArtifacts({
context,
page,
secrets: scenarioSecrets,
requested: new Set(["storage"]),
});
expect(JSON.stringify(result.storage)).not.toContain(secretValue);
expect(result.storage).toMatchObject({
state: "captured",
value: {
cookies: [{ name: "[REDACTED:storage_key]", value_state: "hashed" }],
local_storage: [
{ name: "[REDACTED:storage_key]", value_state: "hashed" },
],
session_storage: [
{ name: "theme", value_state: "redacted-secret", value_sha256: null },
],
},
});
});
+5 -5
View File
@@ -155,20 +155,20 @@ const captureStorage = async (input: {
);
const value = {
cookies: cookies.map((cookie) => ({
name: secrets.redact(cookie.name),
domain: secrets.redact(cookie.domain),
path: secrets.redact(cookie.path),
name: cookie.name,
domain: cookie.domain,
path: cookie.path,
secure: cookie.secure,
http_only: cookie.httpOnly,
same_site: cookie.sameSite,
...secrets.fingerprint(cookie.value),
})),
local_storage: pageStorage.local_storage.map(([name, value]) => ({
name: secrets.redact(name),
name,
...secrets.fingerprint(value),
})),
session_storage: pageStorage.session_storage.map(([name, value]) => ({
name: secrets.redact(name),
name,
...secrets.fingerprint(value),
})),
};
@@ -19,18 +19,6 @@ it("locks one attached browser for spellings that discover the same endpoint", (
);
});
it("locks one attached browser across loopback spellings of one endpoint", () => {
expect(attachedScenarioLeaseKey("http://127.0.0.1:9222", "page-1")).toBe(
attachedScenarioLeaseKey("http://[::1]:9222", "page-1"),
);
expect(attachedScenarioLeaseKey("http://[::1]:9222", "page-1")).not.toBe(
attachedScenarioLeaseKey("http://[::1]:9222", "page-2"),
);
expect(attachedScenarioLeaseKey("http://127.0.0.1:9222", "page-1")).not.toBe(
attachedScenarioLeaseKey("http://127.0.0.1:9223", "page-1"),
);
});
const deferred = <Value>() => {
let resolve: (value: Value | PromiseLike<Value>) => void = () => undefined;
const promise = new Promise<Value>((resolvePromise) => {
@@ -314,76 +302,3 @@ it("cancels same-target queued connection before acquiring a browser", async ()
).rejects.toThrow("connection failed");
expect(connectOverCDP).toHaveBeenCalledTimes(3);
});
it("serializes concurrent attach across loopback spellings of one browser", async () => {
const makeScenario = (endpoint: string) =>
browserScenarioSchema.parse({
browser: { mode: "connect", cdp_endpoint: endpoint, target_id: "page-1" },
start_url: { url: "https://example.test" },
actions: [
{
step_id: "wait",
action: "wait_for_timeout",
duration_ms: 1,
},
],
});
const firstConnection =
deferred<Pick<Browser, "contexts" | "close" | "version">>();
let rejectFirstConnection: ((cause: Error) => void) | undefined;
const failingConnection = new Promise<never>((_resolve, reject) => {
rejectFirstConnection = reject;
});
const firstStarted = deferred<void>();
const endpoints: string[] = [];
const connectOverCDP = vi.fn((endpoint: string) => {
endpoints.push(endpoint);
if (endpoints.length === 1) {
firstStarted.resolve(undefined);
return firstConnection.promise;
}
return failingConnection;
});
const launcher = {
connectOverCDP,
launchPersistentContext: async () => {
throw new Error("Unexpected launch");
},
};
const first = openPlaywrightScenarioBrowser(
makeScenario("http://127.0.0.1:9222"),
{},
{ launcher },
);
await firstStarted.promise;
const second = openPlaywrightScenarioBrowser(
makeScenario("http://[::1]:9222"),
{},
{ launcher },
);
const race = await Promise.race([
second.then(
() => "settled" as const,
() => "settled" as const,
),
new Promise((resolve) => setTimeout(() => resolve("queued"), 100)),
]);
// The loopback spelling is the same browser, so the second attach must wait
// for the lease instead of dialing in parallel and being rejected.
expect(race).toBe("queued");
expect(connectOverCDP).toHaveBeenCalledTimes(1);
firstConnection.resolve({
close: vi.fn(async () => undefined),
contexts: vi.fn(() => []),
version: () => "fixture",
});
await expect(first).rejects.toThrow();
if (rejectFirstConnection === undefined)
throw new Error("second connection did not begin");
rejectFirstConnection(new Error("second connection failed"));
await expect(second).rejects.toThrow("second connection failed");
expect(endpoints).toEqual(["http://127.0.0.1:9222", "http://[::1]:9222"]);
});
+2 -9
View File
@@ -11,7 +11,6 @@ import {
import type { BrowserScenario } from "../domain/browserScenario.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { isLiteralLoopbackHostname } from "../domain/browserObservation.js";
import { BrowserObservationError } from "../domain/browserObservationError.js";
import { withPlaywrightExecutionBoundary } from "./PlaywrightExecutionBoundary.js";
@@ -190,14 +189,8 @@ const createAttachedScenarioRelease = (
export const attachedScenarioLeaseKey = (
endpoint: string,
targetId: string,
): string => {
const discovery = new URL("/json/version", endpoint);
// One CDP browser serves every loopback stack on one port, so spellings that
// reach it through 127.0.0.1 or ::1 must share a single admission.
if (isLiteralLoopbackHostname(discovery.hostname))
discovery.hostname = "127.0.0.1";
return JSON.stringify([discovery.href, targetId]);
};
): string =>
JSON.stringify([new URL("/json/version", endpoint).href, targetId]);
const acquireAttachedScenario = (
scenario: Extract<BrowserScenario["browser"], { readonly mode: "connect" }>,

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