Compare commits

..
Author SHA1 Message Date
morluto a6de554e2a chore: merge main into intrinsic invocation fixes 2026-10-12 01:29:18 +08:00
morluto 1a322ab75b fix(javascript): preserve intrinsic invocation read identity 2026-10-12 01:22:43 +08:00
Ysopwnablefactory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>Kaoru0822morluto
9d8e42bdd6 fix(javascript): follow actual receivers in nested intrinsic calls (#1912)
Consume arguments per generic function invocation rather than property-chain
depth. Preserve the callable receiver through call/apply, Reflect.apply and
bound invocation. Cover nested mutations and fresh targets through source
analysis and inert production CLI/MCP fixtures.

Fixes #1909.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-10-12 01:22:26 +08:00
Matt Van Hornandmorluto d28b41ea4e feat(javascript): resolve exact package import aliases (#1862)
* feat(javascript): resolve exact package import aliases

Resolve exact #alias specifiers against the importer's enclosing
package.json imports map using the shared condition, array, and null
target selection. Nested packages keep their own maps; missing keys,
explicit nulls, and out-of-scope aliases report a precise reason.
Wildcard, recursive, and external-package import targets remain
unresolved.

* fix(javascript): keep nested import aliases in CLI graphs

Bound nested #alias requires produce application-graph require edges
from the enclosing package. Node reports MODULE_NOT_FOUND when a nested
package.json has no imports field, without inheriting the ancestor map.

* fix(javascript): resolve literal package import keys before path admission

* fix(javascript): preserve import keys and invalid-target fallback

* fix(javascript): preserve unmatched package target arrays

* fix(javascript): retain package target refusal evidence

* test(browser): match real verifier startup budget

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-10-12 01:17:58 +08:00
Itoje Dollarandmorluto e8491e023a fix(artifacts): mark Windows launchable files as host executables (#1824)
Host-file occurrences derived `executable` from POSIX execute bits, which
Windows never reports, so every Windows host file (including PE .exe
images classified as executable) reported `executable: false`.

Derive the fact once through hostExecutable: POSIX hosts keep the execute
bits; Windows marks regular files with the extensions it launches directly
(.exe, .com, .bat, .cmd), without reading the ambient PATHEXT.

Fixes #1819

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-10-12 01:15:35 +08:00
cyanseek 097f0d54af perf(javascript): skip nested callables during fingerprint traversal (#1871) 2026-10-12 01:10:31 +08:00
Itoje Dollar e4ac7bbfc2 fix: order remaining outputs independently of host locale (#1867)
* fix: order remaining outputs independently of host locale

String.prototype.localeCompare without a pinned collation follows the
host's ICU default locale, so the same input could be ordered differently
on different machines. 614fb768 moved canonical domain projections to
compareUnicodeCodePoints; provider, application, catalog, and setup
orderings still used locale collation.

Order every remaining source site by Unicode code point, including Mach-O
symbols, firmware extraction paths, ASAR entries (previously pinned to
"en" collation), evidence ID sets, browser and Electron target, script,
and resource inventories, reconstruction obligations, capability and
provider listings, and setup environment details.

The current tool and prompt catalog names order identically under both
comparators, so the catalog identity digest is unchanged.

* fix(artifacts): order ASAR entries by their portable path

@electron/asar lists host-spelled paths, so code-point order over the raw
spelling still differed by host: "a\b" sorts after "a0" on Windows while
"a/b" sorts before it on POSIX. Pair each listing with its portable
archive path once, order by that path, and keep the host spelling for
@electron/asar calls and adapter keys.
2026-10-12 01:10:01 +08:00
Lluís Ariño 0b7fc40eee fix(contracts): mark foreign execution and device mutation destructive (#1904)
MCP annotations derived destructiveHint only from mayDiscardData, so tools
that run the analysis target or a caller-selected executable
(capture_process_scenario, observe_native_calls) and tools that change an
attached Android device (install/uninstall/push/start/stop) advertised
destructiveHint: false.

Add explicit executesForeignCode and mutatesDevice effect flags, audit them
across all 170 tool effect records, and derive
destructiveHint = mayDiscardData || executesForeignCode || mutatesDevice.
readOnlyHint semantics are unchanged.

Hopper/Ghidra metadata writers (set_address_name, set_addresses_names,
set_bookmark, set_comment, set_inline_comment, annotate_native_function)
can replace or clear existing analyst names and comments, so they now
declare mayDiscardData as well.

A contract test pins the destructive set and requires every tool whose
description mentions running, launching, executing, starting, installing or
uninstalling to declare one of the new flags or carry a reasoned exception,
so wording and effects cannot silently drift. The binary_session effects
output schema carries the new flags.
2026-10-12 01:09:01 +08:00
akushonkamen 7a0140b4aa fix(android): bound inline search Evidence with retained inventory provenance (#1890)
Focused and zero-match search_android_classes responses embedded every
examined class name: JadxSession records each raw list_classes page into
observed calls, those calls ride into Evidence raw_result on the
registration path, and the complete inline Evidence is serialized into
every tool response (issue #1850: 382,435 bytes for one match).

When the server session retains Evidence, record the complete raw-call
record first, then deliver a summary Evidence that keeps the pagination
audit (totals, offsets, page sizes, elided item counts), the unchanged
normalized matches and truthful coverage metadata, and links the
retained complete inventory by Evidence ID. Sessions without retention
keep the complete inline delivery, so complete CLI JSON output is
unchanged and no provenance is discarded.

🤖 Generated with AI assistance (disclosure voluntary per repo policy)
2026-10-12 01:07:22 +08:00
Ysopwnablefactory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>Kaoru0822morluto
9b3e59804d fix(javascript): prove namespace interop before attributing Electron APIs (#1857)
* fix(javascript): prove Electron module namespace conversion

* refactor(javascript): share AST child field metadata

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>

* fix(javascript): retain destructured intrinsic writes

Share one pattern-target walker across lexical definitions, member mutation
tracking and Electron identity writes. Keep overwritten globals unresolved
without treating property keys or shadowed locals as global replacements.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>

* fix(javascript): preserve intrinsic projections and fresh target identity

Resolve known mutators through static binding projections and prove stable
identifier chains to fresh literals before widening unknown mutation targets.
Keep reassigned, uninitialized and member-projected targets conservative.
Cover both review regressions through source tests and inert CLI/MCP fixtures.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>

* fix(javascript): retain fresh function and class target identity

Recognize stable local function, undecorated class and RegExp targets before
widening intrinsic mutations. Keep decorated classes opaque because their
binding value can be replaced, and preserve class-initialization writes.
Cover fresh targets and replacement decorators in inert CLI/MCP fixtures.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>

* fix(javascript): preserve intrinsic alias capture timing

Validate each alias read after initialization and retain the original function capture across copies. Share declaration initializer facts with RPC and Electron analysis, including class declarations used for fresh-target identity. Accept single-statement control blocks while keeping lexical roles and added operations checked. Cover the capture regressions through inert source and public CLI/MCP workflows.

* fix(javascript): respect hoisted fresh function declarations

Function declarations provide fresh targets before their textual position. Retain initialization-order checks for variable and class values, including aliases. Cover the reviewed regression with source controls and the public CLI/MCP fixture.

* fix(javascript): preserve proven interop result projections

* fix(javascript): retain stable declarations and bound intrinsic writes

Keep repeated variable declarations with one unconditional initializer while
rejecting assignments, conditional initialization and multiple values.
Normalize known intrinsic calls, aliases and bound argument prefixes at the
semantic owner, retaining opaque targets without tainting unused bindings or
fresh local objects. Cover both regressions through source and CLI/MCP tests.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>

* fix(javascript): retain bound intrinsic mutation effects

* fix(javascript): preserve bound receivers for intrinsic invocation

* fix(javascript): prove generic binding and invocation effects

* fix(javascript): retain Reflect set receiver effects

---------

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-10-12 01:06:33 +08:00
Dery Ferdika 1769417001 fix(firmware): name missing extractor dependencies in partial extraction (#1879)
Unblob reports a missing external extractor as an
ExtractorDependencyNotFoundReport nested inside a chunk or multi-file
report, and normalizeUnblobReport forwarded that value verbatim into
diagnostics as { input_path, report }. A caller that reached partial
coverage therefore had to decode the raw producer report to learn which
extractor was absent and at which stage, even though the report already
names the dependencies.

Extraction diagnostics now normalize those entries: the named
dependencies are collected from the report and any nested value, the
producing handler is recorded as the stage, and the original report stays
retained for provenance. Entries without a dependency report keep their
previous shape.

Validation: FirmwareReports unit cases cover the chunk-nested and
multi-file-nested dependency reports and the retained raw report;
firmware suite passes; typecheck, oxlint and oxfmt on changed files. Real
Unblob extraction is unverified here because it needs the external
extractor stack.
2026-10-12 01:05:01 +08:00
cyanseek 898d5096f9 perf(javascript): index source-map ignore lists per leaf (#1905) 2026-10-12 01:01:33 +08:00
Ysopwnablefactory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>Kaoru0822
38539a2f4a fix(process): retain owned command cleanup diagnostics (#1907)
Preserve per-member verification failures and sweep uncertainty across
supervisor stop and owned-command failures. Report the observed token
mismatch with its PID coordinates instead of implying PID reuse.

Keep unresolved ownership unsignaled and retain the supervisor for a later
verified stop. Exercise cancellation, timeout and cleanup revalidation with
source-owned process fixtures and cooperative settlement.

Closes #1856

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
2026-10-12 01:00:08 +08:00
Ysopwnablefactory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>Kaoru0822
23d50ea3be fix(managed): bind row budget charges to metadata identities (#1897)
Charge fixed row bookkeeping once per table and row within an admitted
metadata layout. Repeated owner lookups no longer permanently consume
capacity for temporary cursors; distinct rows and failed admissions retain
the existing representation limit and typed failure behavior.

Verify repeated local attribute-constructor lookups through public CLI
metadata/member inspection and preserve the remaining capacity guards.

Closes #1878

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
2026-10-12 00:33:51 +08:00
81 changed files with 3395 additions and 316 deletions
@@ -9,7 +9,10 @@ provenance; inputs and recovered code are never executed. Recovery requires a
caller-supplied Wakaru on Linux x64; see [the recovery guide](https://github.com/morluto/rea/blob/main/docs/javascript-recovery.md).
Use `analyze_javascript_application` directly on the operator-supplied ASAR or
extracted tree. When size is unknown or large and the connected schema advertises
extracted tree. Exact `#alias` specifiers resolve through the importer's
enclosing package `imports` map to package-local files; nested `node_modules`
packages use their own map. Wildcard, recursive, and external-package import
targets stay unresolved with that limitation. When size is unknown or large and the connected schema advertises
`detail`, request `detail: "summary"`. This returns an `inspect_analysis_view`
Evidence record with a distinct ID and a `normalized_result.parent_evidence_id`
for the complete retained application analysis. Source-map contents are part of
+28 -4
View File
@@ -350,10 +350,14 @@ creation. Arguments follow each actual callable invocation rather than property
chain depth; rebinding retains the original bound receiver.
Visibly replaced invocation intrinsics produce unknown effects instead
of using their former call semantics; captured function aliases retain their
earlier identity. Unexamined targets remain unresolved. `Reflect.set` examines
its explicit receiver as well as its target, retaining unknown receiver effects.
Creating an unused binding does not itself mutate an intrinsic. Variable
redeclarations retain a single unconditional initializer
earlier identity. Invocation member reads are checked separately from the earlier
function capture. Comma-expression callees use their final value while all
preceding expressions remain in the effect traversal. Call effects are
classified after callee and argument effects have been collected. Unexamined
targets remain unresolved. `Reflect.set` examines its explicit receiver as well
as its target, retaining unknown receiver effects. Creating an unused binding
does not itself mutate an intrinsic. Variable redeclarations retain a single
unconditional initializer
when they introduce no assignment or second initializer.
Stable identifier chains to fresh object, array, function,
undecorated class or RegExp syntax keep those targets separate from intrinsic
@@ -454,9 +458,29 @@ such as `./web3:app.js` still names a local artifact.
Package `exports` fallback arrays are supported both at the top level and under
the root `"."` entry. The resolver selects targets in declared order using the
same conditional and invalid-entry handling as nested exports arrays.
Nonempty arrays containing only inactive conditions remain unmatched, allowing
the enclosing condition object to continue to a later active condition.
Empty arrays and explicit null targets keep their blocking outcome.
Refusal evidence distinguishes those source values and retains condition names
from unmatched nested targets rather than reporting array indices.
For imports and requires, the active Node conditions include `module-sync`;
earlier active conditions retain precedence over later ones.
Exact package-private `#alias` specifiers resolve against the importer's
enclosing `package.json` `imports` map — the nearest same-container package
scope, stopping at a `node_modules` directory so a nested package cannot inherit
an ancestor's aliases. Selected targets are package-local `./` files with no
extension or index fallback, using the same condition, array, and null selection
as exports subpaths. A missing key, explicit null, or out-of-scope alias keeps
an unresolved edge with that reason. Wildcard keys (`#internal/*`), recursive
`#` targets, and external-package import targets remain unresolved.
Exact keys such as `#/x` are literal lookup identities. `#` and names ending
in `/` are invalid. Imports arrays skip invalid parent-relative, absolute, and
URL targets before selecting a later package-local file; an unsupported bare
package or recursive alias keeps its unresolved outcome rather than selecting
a later fallback.
ESM relative module paths and selected package exports targets use URL suffix handling
and one percent-decoding pass. CommonJS relative paths and legacy package main
fields retain literal filename punctuation. Exports targets must start with
+7 -1
View File
@@ -450,7 +450,13 @@ Tool annotations describe effects and are hints, not authorization controls
([MCP ToolAnnotations](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations)).
`readOnlyHint` includes session state: an analysis call that records additive
Evidence is marked non-read-only even when it leaves the target unchanged.
`destructiveHint` describes possible data loss, not ordinary Evidence recording.
`destructiveHint` is true when a tool may discard data (overwriting or clearing
analyst metadata, replacing files, dropping session state), runs or drives code
REA does not own (`executesForeignCode`: process, LLDB, Electron, browser, and
native UI scenarios), or changes an attached Android device (`mutatesDevice`:
push, install, uninstall, start, and stop). Ordinary Evidence recording is not
destructive. The effect record in `binary_session` and the generated catalog
carries each flag separately.
Effect metadata covers possible behavior across supported inputs: DMG inventory
can launch `hdiutil` and create an owned temporary mount directory; extraction
creates a fresh output directory on every call. Comparing supplied web captures
+2 -1
View File
@@ -20,6 +20,7 @@ import {
clientRequirementsFor,
NO_CLIENT_FEATURES,
} from "./CapabilityClientRequirements.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
const statusSchema = z.object({
open: z.boolean(),
@@ -210,7 +211,7 @@ export const buildCapabilityInventory = (
reason: availability.reason,
remediation: availability.remediation,
};
}).sort((left, right) => left.name.localeCompare(right.name));
}).sort((left, right) => compareUnicodeCodePoints(left.name, right.name));
};
const availabilityFor = (context: AvailabilityContext): Availability => {
@@ -18,6 +18,7 @@ import { z } from "zod";
import { PRODUCT_IDENTITY } from "../identity.js";
import type { SetupClient } from "./SupportedClients.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
export type ClientConfigurationFormat = NonNullable<SetupClient["format"]>;
export type ClientServersKey = "mcp_servers" | "mcpServers" | "mcp" | "servers";
@@ -63,7 +64,7 @@ const normalizeConfigurationValue = (value: unknown): unknown => {
return value;
return Object.fromEntries(
Object.entries(value)
.sort(([left], [right]) => left.localeCompare(right))
.sort(([left], [right]) => compareUnicodeCodePoints(left, right))
.map(([key, nested]) => [key, normalizeConfigurationValue(nested)]),
);
};
@@ -8,6 +8,7 @@ import {
type ClientConfigurationDocument,
} from "./ClientConfigurationDocument.js";
import { PRODUCT_IDENTITY } from "../identity.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
/** Read explicit REA overrides without dropping peers when one value is invalid. */
export const clientRegistrationEnvironment = (
@@ -47,7 +48,7 @@ export const clientRegistrationEnvironment = (
return ok(
Object.fromEntries(
Object.entries(environment).sort(([left], [right]) =>
left.localeCompare(right),
compareUnicodeCodePoints(left, right),
),
),
);
+2 -1
View File
@@ -25,6 +25,7 @@ import {
supportedClients,
} from "./SupportedClients.js";
import type { SetupClient } from "./SupportedClients.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
interface ClientRegistrationStatusBase {
readonly client: string;
@@ -184,7 +185,7 @@ export const readClientRegistrationStatuses = async (
}
}
return statuses.sort((left, right) =>
left.client.localeCompare(right.client),
compareUnicodeCodePoints(left.client, right.client),
);
};
@@ -18,6 +18,7 @@ import {
semanticObligationPolicy,
type ReconstructionObligationCandidatePolicy,
} from "./ReconstructionObligationPolicies.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
type CandidateFields = Omit<
ReconstructionObligation,
@@ -54,7 +55,7 @@ export const deriveReconstructionObligationCandidates = (
addCandidate(candidates, reviewedCandidate(obligation, records));
return {
candidates: [...candidates.values()].sort((left, right) =>
left.obligation_id.localeCompare(right.obligation_id),
compareUnicodeCodePoints(left.obligation_id, right.obligation_id),
),
limitations: [...limitations].sort(),
};
@@ -430,7 +431,7 @@ const uniqueBy = <Value>(
key: (value: Value) => string,
): Value[] =>
[...new Map(values.map((value) => [key(value), value])).values()].sort(
(left, right) => key(left).localeCompare(key(right)),
(left, right) => compareUnicodeCodePoints(key(left), key(right)),
);
const obligationId = (key: string): string =>
@@ -3,6 +3,7 @@ import type {
ReconstructionObligationManifest,
} from "../domain/reconstructionObligationLedgerSchemas.js";
import type { Evidence } from "../domain/evidence.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
type Diagnostic = ReconstructionObligation["diagnostics"][number];
type Binding = NonNullable<ReconstructionObligation["binding"]>;
@@ -50,7 +51,8 @@ export const uniqueObligationDiagnostics = (
]),
).values(),
].sort((left, right) =>
`${left.code}:${left.detail}`.localeCompare(
compareUnicodeCodePoints(
`${left.code}:${left.detail}`,
`${right.code}:${right.detail}`,
),
);
@@ -36,6 +36,7 @@ import {
obligationReports,
summarizeObligations,
} from "./ReconstructionObligationLedgerProjection.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
type Diagnostic = ReconstructionObligation["diagnostics"][number];
type Binding = NonNullable<ReconstructionObligation["binding"]>;
@@ -60,7 +61,7 @@ export const evaluateReconstructionObligationLedger = ({
}): ReconstructionObligationLedger => {
const bundle = parseEvidenceBundle(bundleInput);
const allCandidates = [...candidatesInput].sort((left, right) =>
left.obligation_id.localeCompare(right.obligation_id),
compareUnicodeCodePoints(left.obligation_id, right.obligation_id),
);
const orphanManifestIds = findOrphanManifestIds(allCandidates, manifest);
const candidates = allCandidates;
@@ -2,6 +2,7 @@ import type { Evidence } from "../domain/evidence.js";
import type { ReconstructionObligation } from "../domain/reconstructionObligationLedgerSchemas.js";
import { evidenceSupportsOriginalAuthority } from "./ReconstructionObligationAuthority.js";
import type { ReconstructionObligationCandidate } from "./ReconstructionObligationCandidates.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
type Binding = NonNullable<ReconstructionObligation["binding"]>;
type Diagnostic = ReconstructionObligation["diagnostics"][number];
@@ -21,7 +22,8 @@ export const originalCasesFor = (
),
).values(),
].sort((left, right) =>
`${left.kind}:${left.evidence_id}:${left.location}`.localeCompare(
compareUnicodeCodePoints(
`${left.kind}:${left.evidence_id}:${left.location}`,
`${right.kind}:${right.evidence_id}:${right.location}`,
),
);
+2 -1
View File
@@ -15,6 +15,7 @@ import type {
} from "./SetupTypes.js";
import type { SetupClient } from "./SupportedClients.js";
import type { DoctorReport } from "./Doctor.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
/** Read-only setup facts shared by client selection and preflight. */
export interface SetupDiscovery {
@@ -308,7 +309,7 @@ const clientConfigurationDetail = (
installHopper: boolean,
): string => {
const entries = Object.entries(environment)
.sort(([left], [right]) => left.localeCompare(right))
.sort(([left], [right]) => compareUnicodeCodePoints(left, right))
.map(([name, value]) => `${name}=${value}`);
const environmentDetail =
entries.length === 0
@@ -1,4 +1,5 @@
import type { DoctorProviderInspection } from "./Doctor.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
/** Preserve adapter-published settings independently of runtime readiness. */
export const providerRegistrationEnvironment = (
@@ -9,5 +10,5 @@ export const providerRegistrationEnvironment = (
.flatMap(({ registrationEnvironment }) =>
Object.entries(registrationEnvironment),
)
.sort(([left], [right]) => left.localeCompare(right)),
.sort(([left], [right]) => compareUnicodeCodePoints(left, right)),
);
+2 -1
View File
@@ -6,6 +6,7 @@ import {
HermesClientPathError,
resolveHermesClientHome,
} from "./HermesClientHome.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
/** One supported client configuration location. */
export interface SetupClient {
@@ -642,6 +643,6 @@ export const clientSkillDirectories = (
});
}
return [...destinations.values()].sort((left, right) =>
left.directory.localeCompare(right.directory),
compareUnicodeCodePoints(left.directory, right.directory),
);
};
@@ -0,0 +1,120 @@
import type { EvidenceWriter } from "../investigation/InvestigationRecordPort.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { JsonValue } from "../../domain/jsonValue.js";
import { ok, type Result } from "../../domain/result.js";
/**
* Complete class-inventory pages dominate raw-call provenance for focused
* searches: one traversal embeds every examined class name regardless of the
* match count. The summary keeps the pagination audit inline (totals, page
* offsets and sizes, elided item counts) and links the retained record that
* still carries the complete inventory.
*/
const elideInventoryText = (text: string): string | undefined => {
let page: JsonValue;
try {
page = JSON.parse(text) as JsonValue;
} catch {
return undefined;
}
if (
typeof page !== "object" ||
page === null ||
Array.isArray(page) ||
!Array.isArray(page.items)
)
return undefined;
const { items, ...audited } = page;
return JSON.stringify({ ...audited, items_omitted: items.length });
};
/** Replace inventoried page bodies with their pagination audit. */
const summarizeInventoryCall = (call: JsonValue): JsonValue => {
if (
typeof call !== "object" ||
call === null ||
Array.isArray(call) ||
call.operation !== "list_classes"
)
return call;
const response = call.response;
if (
typeof response !== "object" ||
response === null ||
Array.isArray(response) ||
!Array.isArray(response.content)
)
return call;
let elided = false;
const content = response.content.map((entry: JsonValue) => {
if (
typeof entry !== "object" ||
entry === null ||
Array.isArray(entry) ||
typeof entry.text !== "string"
)
return entry;
const summarized = elideInventoryText(entry.text);
if (summarized === undefined) return entry;
elided = true;
return { ...entry, text: summarized };
});
return elided
? { ...call, inventory_elided: true, response: { ...response, content } }
: call;
};
/**
* Retain the complete search Evidence — full raw provider calls included —
* in the session record, then deliver a bounded summary Evidence inline.
* Callers without a retaining session keep the complete inline delivery, so
* complete CLI JSON output is unchanged. Coverage metadata stays truthful in
* both copies: the examined inventory is never rewritten to matched-only.
*/
export const summarizeRetainedAndroidSearch = (
evidence: Evidence,
recordEvidence: EvidenceWriter["recordEvidence"] | undefined,
): Result<Evidence, AnalysisError> => {
if (recordEvidence === undefined) return ok(evidence);
const recorded = recordEvidence(evidence);
if (!recorded.ok) return recorded;
const subject = evidence.subject;
const raw = evidence.raw_result;
const summarized: JsonValue =
raw === null ||
typeof raw !== "object" ||
Array.isArray(raw) ||
!Array.isArray(raw.calls)
? raw
: {
...raw,
complete_evidence_id: evidence.evidence_id,
calls: raw.calls.map(summarizeInventoryCall),
};
return ok(
createEvidence(
subject === null
? undefined
: {
path: subject.local_path,
sha256: subject.digest.sha256,
format: subject.format,
...(subject.architecture === null
? {}
: { architecture: subject.architecture }),
},
evidence.provider,
{
operation: evidence.operation,
parameters: evidence.parameters,
result: evidence.normalized_result,
rawResult: summarized,
confidence: evidence.confidence,
limitations: evidence.limitations,
locations: evidence.locations,
evidenceLinks: [evidence.evidence_id],
},
),
);
};
@@ -25,6 +25,7 @@ import {
evaluateAnalysisProviderCandidate,
type AnalysisProviderCandidateEvaluation,
} from "./AnalysisProviderEvaluation.js";
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
/** Deterministic discovery truth for one configured deep provider. */
export interface AnalysisProviderCandidateStatus {
@@ -109,12 +110,14 @@ export class AnalysisProviderRegistry {
}
this.#providers = Object.freeze(
[...providers].sort((left, right) =>
left.identity().id.localeCompare(right.identity().id),
compareUnicodeCodePoints(left.identity().id, right.identity().id),
),
);
this.#byId = byId;
this.#declaredOperations = Object.freeze(
[...declaredOperations].sort((left, right) => left.localeCompare(right)),
[...declaredOperations].sort((left, right) =>
compareUnicodeCodePoints(left, right),
),
);
}
+11 -4
View File
@@ -11,6 +11,7 @@ import type {
SessionProviderRoute,
SessionProviderRouter,
} from "./SessionProviderRouter.js";
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
interface BinarySessionStatusInput {
readonly target: BinaryTarget | undefined;
@@ -39,7 +40,9 @@ export const binarySessionStatus = ({
}: BinarySessionStatusInput): JsonValue => {
const capabilities = [...route.capabilities.values()]
.filter(({ operation }) => operation !== "inventory_artifact")
.sort((left, right) => left.operation.localeCompare(right.operation))
.sort((left, right) =>
compareUnicodeCodePoints(left.operation, right.operation),
)
.map((descriptor) => {
const unavailable = runtimeUnavailability.get(descriptor.operation);
return unavailable === undefined
@@ -69,7 +72,9 @@ export const binarySessionStatus = ({
capabilities: candidate.capabilities
.slice()
.filter(({ operation }) => operation !== "inventory_artifact")
.sort((left, right) => left.operation.localeCompare(right.operation))
.sort((left, right) =>
compareUnicodeCodePoints(left.operation, right.operation),
)
.map(capabilityStatus),
}));
const common = {
@@ -102,7 +107,9 @@ const requestActivityStatus = (
) => {
const providers = snapshots
.slice()
.sort((left, right) => left.provider.id.localeCompare(right.provider.id))
.sort((left, right) =>
compareUnicodeCodePoints(left.provider.id, right.provider.id),
)
.map(({ provider, active, queuedRequests }) => ({
provider: providerSummary(provider),
active:
@@ -150,7 +157,7 @@ const processLineageStatus = (
snapshots: snapshots
.slice()
.sort((left, right) =>
left.provider.id.localeCompare(right.provider.id),
compareUnicodeCodePoints(left.provider.id, right.provider.id),
)
.map(({ provider, observation }) => ({
provider: providerSummary(provider),
+5 -4
View File
@@ -10,6 +10,7 @@ import type {
ProviderIdentity,
} from "../AnalysisProvider.js";
import { closeAnalysisClient } from "./AnalysisClientCleanup.js";
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
/** Synthetic identity for a deterministic provider set. */
const compositeProviderIdentity = (
@@ -53,8 +54,8 @@ export class CompositeProvider implements AnalysisProvider {
this.#capabilities = Object.freeze(
capabilities.sort(
(left, right) =>
left.operation.localeCompare(right.operation) ||
left.provider.id.localeCompare(right.provider.id),
compareUnicodeCodePoints(left.operation, right.operation) ||
compareUnicodeCodePoints(left.provider.id, right.provider.id),
),
);
}
@@ -122,13 +123,13 @@ export class CompositeProvider implements AnalysisProvider {
[...clients.values()]
.flatMap((client) => client.runtimeLineageSnapshots?.() ?? [])
.sort((left, right) =>
left.provider.id.localeCompare(right.provider.id),
compareUnicodeCodePoints(left.provider.id, right.provider.id),
),
requestActivitySnapshots: () =>
[...clients.values()]
.flatMap((client) => client.requestActivitySnapshots?.() ?? [])
.sort((left, right) =>
left.provider.id.localeCompare(right.provider.id),
compareUnicodeCodePoints(left.provider.id, right.provider.id),
),
operationHealthSnapshot: () => {
for (const client of clients.values()) {
@@ -24,6 +24,7 @@ import {
type UpdateUnknownInput,
} from "../../domain/residualUnknown.js";
import { err, ok, type Result } from "../../domain/result.js";
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
type EvidenceLedgerFailure = EvidenceIntegrityError;
type RecordResult = Result<"added" | "duplicate", EvidenceLedgerFailure>;
@@ -321,7 +322,9 @@ export class EvidenceLedger {
unknown.severity === filters.severity) &&
(filters.domain === undefined || unknown.domain === filters.domain),
)
.sort((left, right) => left.unknown_id.localeCompare(right.unknown_id))
.sort((left, right) =>
compareUnicodeCodePoints(left.unknown_id, right.unknown_id),
)
.map((unknown) => structuredClone(unknown));
}
@@ -868,6 +868,365 @@ describe("package exports exact targets", () => {
});
});
describe("package import alias resolution", () => {
it.each(["import", "require"] as const)(
"resolves an exact #%s alias from the enclosing package imports map",
(moduleKind) => {
const files = aliasFiles({
"package.json": JSON.stringify({
imports: { "#config": "./config.cjs" },
}),
"main.js": "",
"config.cjs": "",
});
expect(
resolve({
declaredPath: "#config",
sourcePath: "main.js",
context: "module-specifier",
moduleKind,
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "config.cjs",
declared_path: "#config",
});
},
);
it("resolves an alias from a nested file through the enclosing package root", () => {
const files = aliasFiles({
"package.json": JSON.stringify({
imports: { "#config": "./config.cjs" },
}),
"src/main.js": "",
"config.cjs": "",
});
expect(
resolve({
declaredPath: "#config",
sourcePath: "src/main.js",
context: "module-specifier",
moduleKind: "require",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "config.cjs",
});
});
it("uses a nested package imports map rather than the application root", () => {
const files = aliasFiles({
"package.json": JSON.stringify({
imports: { "#config": "./root.cjs" },
}),
"root.cjs": "",
"node_modules/fixture/package.json": JSON.stringify({
imports: { "#config": "./local.cjs" },
}),
"node_modules/fixture/index.js": "",
"node_modules/fixture/local.cjs": "",
});
expect(
resolve({
declaredPath: "#config",
sourcePath: "node_modules/fixture/index.js",
context: "module-specifier",
moduleKind: "require",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "node_modules/fixture/local.cjs",
});
});
it("does not inherit an ancestor imports map across a nested package.json", () => {
const files = aliasFiles({
"package.json": JSON.stringify({
imports: { "#config": "./root.cjs" },
}),
"root.cjs": "",
"node_modules/fixture/package.json": "{}",
"node_modules/fixture/index.js": "",
});
const outcome = resolve({
declaredPath: "#config",
sourcePath: "node_modules/fixture/index.js",
context: "module-specifier",
moduleKind: "require",
files,
});
expect(outcome).toMatchObject({
resolution_status: "external",
resolved_path: null,
});
expect(outcome.limitations.join(" ")).toContain(
"node_modules/fixture/package.json",
);
expect(outcome.limitations.join(" ")).not.toContain("root.cjs");
});
it("does not apply a nested package map to the application root importer", () => {
const files = aliasFiles({
"package.json": JSON.stringify({
imports: { "#config": "./root.cjs" },
}),
"main.js": "",
"root.cjs": "",
"node_modules/fixture/package.json": JSON.stringify({
imports: { "#config": "./local.cjs" },
}),
"node_modules/fixture/local.cjs": "",
});
expect(
resolve({
declaredPath: "#config",
sourcePath: "main.js",
context: "module-specifier",
moduleKind: "require",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "root.cjs",
});
});
});
describe("package import alias target selection", () => {
it("selects import and require conditions from an imports target", () => {
const files = aliasFiles({
"package.json": JSON.stringify({
imports: {
"#config": {
import: "./config.mjs",
require: "./config.cjs",
default: "./fallback.js",
},
},
}),
"main.js": "",
"config.mjs": "",
"config.cjs": "",
"fallback.js": "",
});
expect(
resolve({
declaredPath: "#config",
sourcePath: "main.js",
context: "module-specifier",
moduleKind: "import",
files,
}).resolved_path,
).toBe("config.mjs");
expect(
resolve({
declaredPath: "#config",
sourcePath: "main.js",
context: "module-specifier",
moduleKind: "require",
files,
}).resolved_path,
).toBe("config.cjs");
});
it("resolves array import targets at their first string entry", () => {
const files = aliasFiles({
"package.json": JSON.stringify({
imports: { "#config": [{ import: "./missing.mjs" }, "./config.cjs"] },
}),
"main.js": "",
"config.cjs": "",
});
expect(
resolve({
declaredPath: "#config",
sourcePath: "main.js",
context: "module-specifier",
moduleKind: "require",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "config.cjs",
});
});
it("does not add an extension or index to a selected import target", () => {
const files = aliasFiles({
"package.json": JSON.stringify({
imports: { "#config": "./config" },
}),
"main.js": "",
"config.cjs": "",
"config/index.js": "",
});
const outcome = resolve({
declaredPath: "#config",
sourcePath: "main.js",
context: "module-specifier",
moduleKind: "require",
files,
});
expect(outcome).toMatchObject({
resolution_status: "not-found",
resolved_path: null,
});
expect(outcome.limitations.join(" ")).toContain(
"import targets are exact files",
);
});
});
describe("package import alias refusals", () => {
it("reports a missing exact alias without looking in another package", () => {
const files = aliasFiles({
"package.json": JSON.stringify({
imports: { "#config": "./config.cjs" },
}),
"main.js": "",
"config.cjs": "",
});
const outcome = resolve({
declaredPath: "#other",
sourcePath: "main.js",
context: "module-specifier",
moduleKind: "require",
files,
});
expect(outcome).toMatchObject({
resolution_status: "external",
resolved_path: null,
});
expect(outcome.limitations.join(" ")).toContain("#other");
expect(outcome.limitations.join(" ")).toContain("#config");
});
it("reports an explicit null import target as blocked", () => {
const files = aliasFiles({
"package.json": JSON.stringify({
imports: { "#config": null },
}),
"main.js": "",
"config.cjs": "",
});
const outcome = resolve({
declaredPath: "#config",
sourcePath: "main.js",
context: "module-specifier",
moduleKind: "require",
files,
});
expect(outcome).toMatchObject({
resolution_status: "external",
resolved_path: null,
});
expect(outcome.limitations.join(" ")).toContain("explicit null");
});
it("leaves wildcard import aliases unresolved", () => {
const files = aliasFiles({
"package.json": JSON.stringify({
imports: { "#internal/*": "./src/*.js" },
}),
"main.js": "",
"src/util.js": "",
});
const outcome = resolve({
declaredPath: "#internal/util",
sourcePath: "main.js",
context: "module-specifier",
moduleKind: "import",
files,
});
expect(outcome).toMatchObject({
resolution_status: "external",
resolved_path: null,
});
expect(outcome.limitations.join(" ")).toMatch(/wildcard/i);
});
it("leaves recursive and external-package import targets unresolved", () => {
const files = aliasFiles({
"package.json": JSON.stringify({
imports: { "#loop": "#config", "#dep": "fixture" },
}),
"main.js": "",
"node_modules/fixture/index.js": "",
});
const recursive = resolve({
declaredPath: "#loop",
sourcePath: "main.js",
context: "module-specifier",
moduleKind: "require",
files,
});
const external = resolve({
declaredPath: "#dep",
sourcePath: "main.js",
context: "module-specifier",
moduleKind: "require",
files,
});
expect(recursive).toMatchObject({
resolution_status: "external",
resolved_path: null,
});
expect(recursive.limitations.join(" ")).toMatch(/recursive/i);
expect(external).toMatchObject({
resolution_status: "external",
resolved_path: null,
});
expect(external.limitations.join(" ")).toMatch(/external-package/i);
});
it("rejects reserved hash specifiers", () => {
const files = aliasFiles({
"package.json": JSON.stringify({
imports: { "#config": "./config.cjs" },
}),
"main.js": "",
"config.cjs": "",
});
expect(
resolve({
declaredPath: "#",
sourcePath: "main.js",
context: "module-specifier",
moduleKind: "import",
files,
}),
).toMatchObject({ resolution_status: "rejected", resolved_path: null });
});
it("does not use a foreign-container enclosing package.json", () => {
const files = fileMap([
file(
"package.json",
"other",
JSON.stringify({ imports: { "#config": "./config.cjs" } }),
),
file("main.js", "root"),
file("config.cjs", "root"),
]);
const outcome = resolve({
declaredPath: "#config",
sourcePath: "main.js",
context: "module-specifier",
moduleKind: "require",
files,
});
expect(outcome).toMatchObject({
resolution_status: "external",
resolved_path: null,
});
expect(outcome.limitations.join(" ")).toContain("package scopes");
});
});
describe("directory package entrypoint precedence", () => {
it.each([
["require", '{"main":"actual.cjs"}', "actual.cjs"],
@@ -1211,6 +1570,15 @@ const file = (
: { included: true, value: text },
});
const aliasFiles = (
entries: Readonly<Record<string, string | null>>,
): ReturnType<typeof fileMap> =>
fileMap(
Object.entries(entries).map(([path, text]) =>
file(path, "root", text ?? ""),
),
);
describe("exact HTML resource resolution", () => {
it.each([
["extension", ["app.js"]],
@@ -14,6 +14,11 @@ import {
percentDecodeUrlPath,
stripQueryAndFragment,
} from "../../domain/artifactPathSyntax.js";
import {
classifyPackageImportSpecifier,
classifyPackageImportTargetString,
lookupExactPackageImport,
} from "../../domain/javascript/javascriptPackageImportAliases.js";
type ArtifactPathResolutionContext =
| "package-entrypoint"
@@ -103,6 +108,13 @@ export const resolveArtifactPathByContext = (
};
const resolvePath = (input: ResolveArtifactPathInput): CandidateResolution => {
// Package import keys are literal lookup identities, not artifact paths.
// The selected target is admitted separately by resolveExportTarget.
if (
input.context === "module-specifier" &&
input.declaredPath.startsWith("#")
)
return resolvePackageImportAlias(input, input.declaredPath);
const rejected = rejectDeclaration(input.declaredPath);
if (rejected !== null) return rejected;
const candidate = contextualCandidate(input);
@@ -202,9 +214,9 @@ const bareModuleCandidate = (
declared: string,
): CandidateResolution => {
const packageName = barePackageName(declared);
if (packageName === null || isBuiltin(declared) || declared.startsWith("#"))
if (packageName === null || isBuiltin(declared))
return unresolvedCandidate("external", [
"The bare specifier is a Node builtin, package import map, or invalid package name.",
"The bare specifier is a Node builtin or invalid package name.",
]);
if (input.moduleKind === "import" && packageName.includes("%"))
return unresolvedCandidate("rejected", [
@@ -235,6 +247,115 @@ const bareModuleCandidate = (
]);
};
/**
* Nearest same-container package.json, stopping at a `node_modules` directory
* so a nested package cannot inherit an ancestor's map.
*/
const enclosingPackageMetadata = (
input: ResolveArtifactPathInput,
):
| Extract<PackageMetadata, { readonly kind: "available" | "unavailable" }>
| { readonly kind: "none" } => {
let directory = posix.dirname(input.sourcePath);
while (posix.basename(directory) !== "node_modules") {
const metadata = readPackageMetadata(input, directory);
if (metadata.kind !== "absent") return metadata;
if (directory === "." || directory === "") break;
directory = posix.dirname(directory);
}
return { kind: "none" };
};
/**
* Resolve an exact `#alias` against the importer's enclosing `imports` map.
* Selected relative targets are exact files; patterns, recursive aliases, and
* external-package targets stay unresolved without falling through.
*/
const resolvePackageImportAlias = (
input: ResolveArtifactPathInput,
specifier: string,
): CandidateResolution => {
const classified = classifyPackageImportSpecifier(specifier);
if (classified.kind === "invalid")
return unresolvedCandidate("rejected", [
`The package import specifier ${JSON.stringify(specifier)} is invalid; "#" and specifiers that end with "/" are not valid import aliases.`,
]);
if (classified.kind === "pattern")
return unresolvedCandidate("external", [
`Wildcard and directory package import aliases remain unresolved; ${JSON.stringify(specifier)} is not an exact imports key.`,
]);
const metadata = enclosingPackageMetadata(input);
if (metadata.kind === "none")
return unresolvedCandidate("external", [
`No enclosing package.json defines package import alias ${specifier}; package import maps do not cross package scopes.`,
]);
if (metadata.kind === "unavailable")
return unresolvedCandidate("unavailable", [metadata.limitation]);
const lookup = lookupExactPackageImport(metadata.imports, specifier);
if (lookup.kind === "undefined-map")
return unresolvedCandidate("external", [
`Package metadata ${metadata.path} does not define package import alias ${specifier}.`,
]);
if (lookup.kind === "missing-key")
return unresolvedCandidate("external", [
`Package metadata ${metadata.path} does not define package import alias ${specifier}; it declares ${lookup.declared.join(", ") || "no imports keys"}.`,
]);
if (lookup.kind === "pattern-unresolved")
return unresolvedCandidate("external", [
`Wildcard package import aliases remain unresolved; package metadata ${metadata.path} has no exact imports key ${specifier}.`,
]);
const selected = selectPackageImportTarget(lookup.target, input.moduleKind);
if (selected.status === "rejected")
return unresolvedCandidate("rejected", [
`Package metadata ${metadata.path}: ${selected.limitation}`,
]);
if (selected.status === "unmatched")
return unresolvedCandidate("external", [
`Package metadata ${metadata.path} declares no imports target for alias ${specifier} under the active conditions; it declares ${selected.declared.join(", ") || "no conditions"}.`,
]);
if (selected.status === "blocked")
return unresolvedCandidate("external", [
`Package metadata ${metadata.path} blocks import alias ${specifier} with ${selected.cause === "null" ? "an explicit null imports target" : "an empty imports target array"}.`,
]);
if (selected.status === "non-relative") {
const target = classifyPackageImportTargetString(selected.value);
return unresolvedCandidate("external", [
target.kind === "recursive"
? `Recursive package import aliases remain unresolved; package metadata ${metadata.path} maps ${specifier} to ${JSON.stringify(target.target)}.`
: `External-package import targets remain unresolved; package metadata ${metadata.path} maps ${specifier} to ${JSON.stringify(target.target)}.`,
]);
}
return resolveExportTarget(input, metadata.path, selected.value, "imports");
};
const selectPackageImportTarget = (
value: unknown,
moduleKind: ResolveArtifactPathInput["moduleKind"],
):
| { readonly status: "value"; readonly value: string }
| { readonly status: "non-relative"; readonly value: string }
| { readonly status: "blocked"; readonly cause: PackageTargetBlockCause }
| { readonly status: "unmatched"; readonly declared: readonly string[] }
| { readonly status: "rejected"; readonly limitation: string } => {
const selected = selectExportTarget(
value,
packageExportConditions(moduleKind),
"imports",
);
if (selected.kind === "invalid" || selected.kind === "invalid-config")
return { status: "rejected", limitation: selected.limitation };
if (selected.kind === "unmatched")
return {
status: "unmatched",
declared: selected.declared,
};
if (selected.kind === "blocked")
return { status: "blocked", cause: selected.cause };
if (selected.kind === "non-relative")
return { status: "non-relative", value: selected.value };
return { status: "value", value: selected.value };
};
/** Self references use the nearest package scope before dependency lookup. */
const commonJsSelfCandidate = (
input: ResolveArtifactPathInput,
@@ -242,35 +363,22 @@ const commonJsSelfCandidate = (
): CandidateResolution | null => {
if (input.moduleKind !== "require" || !input.files.has(input.sourcePath))
return null;
let directory = posix.dirname(input.sourcePath);
while (posix.basename(directory) !== "node_modules") {
const metadata = readPackageMetadata(input, directory);
if (metadata.kind === "unavailable")
return unresolvedCandidate("unavailable", [metadata.limitation]);
if (metadata.kind === "available") {
if (
metadata.name === undefined ||
metadata.exports === undefined ||
(declared !== metadata.name &&
!declared.startsWith(`${metadata.name}/`))
)
return null;
const subpath =
declared === metadata.name
? "."
: `.${declared.slice(metadata.name.length)}`;
// Self resolution does not apply the CommonJS dependency-name matcher.
return resolvePackageExports(
input,
metadata.path,
subpath,
metadata.exports,
);
}
if (directory === "." || directory === "") break;
directory = posix.dirname(directory);
}
return null;
const metadata = enclosingPackageMetadata(input);
if (metadata.kind === "none") return null;
if (metadata.kind === "unavailable")
return unresolvedCandidate("unavailable", [metadata.limitation]);
if (
metadata.name === undefined ||
metadata.exports === undefined ||
(declared !== metadata.name && !declared.startsWith(`${metadata.name}/`))
)
return null;
const subpath =
declared === metadata.name
? "."
: `.${declared.slice(metadata.name.length)}`;
// Self resolution does not apply the CommonJS dependency-name matcher.
return resolvePackageExports(input, metadata.path, subpath, metadata.exports);
};
/** Package roots and exact subpaths share metadata and exports selection. */
@@ -324,16 +432,17 @@ const resolvePackageExports = (
]);
if (exported.status === "blocked")
return unresolvedCandidate("external", [
`Directory package metadata ${packagePath} blocks subpath ${subpath} with an explicit null exports target.`,
`Directory package metadata ${packagePath} blocks subpath ${subpath} with ${exported.cause === "null" ? "an explicit null exports target" : "an empty exports target array"}.`,
]);
return resolveExportTarget(input, packagePath, exported.value);
};
/** An exports target is a URL naming one exact file for both Node loaders. */
/** An exports or import target is a URL naming one exact file for both Node loaders. */
const resolveExportTarget = (
input: ResolveArtifactPathInput,
packagePath: string,
target: string,
mapKind: "exports" | "imports" = "exports",
): CandidateResolution => {
const rejected = rejectDeclaration(target);
if (rejected !== null) return rejected;
@@ -343,7 +452,7 @@ const resolveExportTarget = (
if (typeof candidate !== "string") return candidate;
return (
resolveFileCandidates(input, [candidate]) ??
exactExportsTargetNotFound(candidate)
exactPackageTargetNotFound(candidate, mapKind)
);
};
@@ -492,6 +601,7 @@ type PackageMetadata =
readonly path: string;
readonly name: string | undefined;
readonly exports: string | object | undefined;
readonly imports: object | undefined;
readonly main: unknown;
readonly module: unknown;
}
@@ -532,6 +642,7 @@ const readPackageMetadata = (
};
const name = Reflect.get(value, "name");
const exports = Reflect.get(value, "exports");
const imports = Reflect.get(value, "imports");
return {
kind: "available",
path,
@@ -543,6 +654,11 @@ const readPackageMetadata = (
(typeof exports === "object" && exports !== null)
? exports
: undefined,
// Import maps must be non-array objects; other shapes are not a map.
imports:
typeof imports === "object" && imports !== null && !Array.isArray(imports)
? imports
: undefined,
main: Reflect.get(value, "main"),
module: Reflect.get(value, "module"),
};
@@ -644,10 +760,12 @@ const fileCandidates = (candidate: string): readonly string[] => [
const indexCandidates = (candidate: string): readonly string[] =>
EXTENSIONS.map((extension) => posix.join(candidate, `index${extension}`));
type PackageTargetBlockCause = "null" | "empty-array";
type PackageExportOutcome =
| { readonly status: "value"; readonly value: string }
| { readonly status: "rejected"; readonly limitation: string }
| { readonly status: "blocked" }
| { readonly status: "blocked"; readonly cause: PackageTargetBlockCause }
| { readonly status: "unmatched"; readonly declared: readonly string[] };
/** Only exact non-directory keys participate; wildcard expansion is unsupported. */
@@ -687,29 +805,33 @@ const selectPackageExport = (
if (selected.kind === "unmatched")
return {
status: "unmatched",
declared:
typeof target === "object" && target !== null
? Object.keys(target)
: declared,
declared: selected.declared,
};
return selected.kind === "blocked"
? { status: "blocked" }
: { status: "value", value: selected.value };
if (selected.kind === "blocked")
return { status: "blocked", cause: selected.cause };
if (selected.kind === "non-relative")
return {
status: "rejected",
limitation: `The package exports target ${JSON.stringify(selected.value)} must start with "./".`,
};
return { status: "value", value: selected.value };
};
type ExportTargetOutcome =
| { readonly kind: "value"; readonly value: string }
| { readonly kind: "blocked" }
| { readonly kind: "unmatched" }
| { readonly kind: "non-relative"; readonly value: string }
| { readonly kind: "blocked"; readonly cause: PackageTargetBlockCause }
| { readonly kind: "unmatched"; readonly declared: readonly string[] }
| { readonly kind: "invalid"; readonly limitation: string }
| { readonly kind: "invalid-config"; readonly limitation: string };
const invalidExportTarget = (
value: unknown,
reason: string,
mapKind: "exports" | "imports" = "exports",
): ExportTargetOutcome => ({
kind: "invalid",
limitation: `The package exports target ${JSON.stringify(value) ?? String(value)} ${reason}.`,
limitation: `The package ${mapKind === "imports" ? "import" : "exports"} target ${JSON.stringify(value) ?? String(value)} ${reason}.`,
});
// Node checks raw target segments before URL normalization. Compare encoded
@@ -729,50 +851,80 @@ const forbiddenExportSegment = (value: string): string | undefined =>
);
});
const selectStringPackageTarget = (
value: string,
mapKind: "exports" | "imports",
): ExportTargetOutcome => {
if (mapKind === "imports") {
const target = classifyPackageImportTargetString(value);
if (target.kind === "invalid")
return invalidExportTarget(
value,
"cannot be parent-relative, absolute, or a URL",
mapKind,
);
if (target.kind !== "relative") return { kind: "non-relative", value };
} else if (!value.startsWith("./"))
return invalidExportTarget(value, 'must start with "./"', mapKind);
const forbidden = forbiddenExportSegment(value);
return forbidden === undefined
? { kind: "value", value }
: invalidExportTarget(
value,
`contains forbidden path segment ${JSON.stringify(forbidden)} before URL normalization`,
mapKind,
);
};
const selectArrayPackageTarget = (
value: readonly unknown[],
conditions: ReadonlySet<string>,
mapKind: "exports" | "imports",
): ExportTargetOutcome => {
if (value.length === 0) return { kind: "blocked", cause: "empty-array" };
let lastRefusal:
| Extract<ExportTargetOutcome, { readonly kind: "invalid" | "blocked" }>
| undefined;
const declared = new Set<string>();
for (const entry of value) {
const nested = selectExportTarget(entry, conditions, mapKind);
// Node's array fallback catches invalid targets, not invalid configuration.
if (nested.kind === "invalid-config") return nested;
if (nested.kind === "unmatched") {
for (const condition of nested.declared) declared.add(condition);
continue;
}
if (nested.kind === "invalid" || nested.kind === "blocked") {
lastRefusal = nested;
continue;
}
return nested;
}
return lastRefusal ?? { kind: "unmatched", declared: [...declared] };
};
/**
* Resolve a target in Node's declared order. Explicit null blocks an active
* condition, whereas an unmatched nested object permits the next condition.
* An array skips unmatched and invalid entries, stops at its first string, and
* preserves the final invalid-versus-null refusal if no string is selected.
* preserves the last invalid/null outcome if no string is selected. A nonempty
* array of unmatched conditions stays unmatched; an empty array blocks.
*/
const selectExportTarget = (
value: unknown,
conditions: ReadonlySet<string>,
mapKind: "exports" | "imports" = "exports",
): ExportTargetOutcome => {
if (typeof value === "string") {
if (!value.startsWith("./"))
return invalidExportTarget(value, 'must start with "./"');
const forbidden = forbiddenExportSegment(value);
return forbidden === undefined
? { kind: "value", value }
: invalidExportTarget(
value,
`contains forbidden path segment ${JSON.stringify(forbidden)} before URL normalization`,
);
}
if (value === null) return { kind: "blocked" };
if (Array.isArray(value)) {
let invalid: string | null = null;
for (const entry of value) {
const nested = selectExportTarget(entry, conditions);
// Node's array fallback catches invalid targets, not invalid configuration.
if (nested.kind === "invalid-config") return nested;
if (nested.kind === "invalid") {
invalid = nested.limitation;
continue;
}
if (nested.kind === "unmatched") continue;
invalid = null;
if (nested.kind === "value") return nested;
}
return invalid === null
? { kind: "blocked" }
: { kind: "invalid", limitation: invalid };
}
if (typeof value === "string")
return selectStringPackageTarget(value, mapKind);
if (value === null) return { kind: "blocked", cause: "null" };
if (Array.isArray(value))
return selectArrayPackageTarget(value, conditions, mapKind);
if (typeof value !== "object")
return invalidExportTarget(
value,
"must be a relative string, object, array, or null",
mapKind,
);
for (const key of Object.keys(value)) {
const numeric = Number(key);
@@ -782,12 +934,15 @@ const selectExportTarget = (
limitation: `The package exports configuration contains numeric condition key ${JSON.stringify(key)}.`,
};
}
const declared = new Set<string>();
for (const [condition, target] of Object.entries(value)) {
declared.add(condition);
if (!conditions.has(condition)) continue;
const nested = selectExportTarget(target, conditions);
const nested = selectExportTarget(target, conditions, mapKind);
if (nested.kind !== "unmatched") return nested;
for (const name of nested.declared) declared.add(name);
}
return { kind: "unmatched" };
return { kind: "unmatched", declared: [...declared] };
};
/**
@@ -816,11 +971,14 @@ const notFoundCandidate = (): CandidateResolution => ({
],
});
const exactExportsTargetNotFound = (path: string): CandidateResolution => ({
const exactPackageTargetNotFound = (
path: string,
mapKind: "exports" | "imports",
): CandidateResolution => ({
resolvedPath: null,
status: "not-found",
limitations: [
`The selected package exports target ${path} does not exist in the inventoried artifact container; exports targets are exact files, so no extension or directory index was tried.`,
`The selected package ${mapKind === "imports" ? "import" : "exports"} target ${path} does not exist in the inventoried artifact container; ${mapKind === "imports" ? "import" : "exports"} targets are exact files, so no extension or directory index was tried.`,
],
});
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from "vitest";
import { orderAsarListing } from "./AsarArtifactReader.js";
describe("orderAsarListing", () => {
it("orders host-spelled listings by their portable archive path", () => {
const posix = orderAsarListing(["/a0", "/a", "/a/b"], "/");
const windows = orderAsarListing(["\\a0", "\\a", "\\a\\b"], "\\");
// "/" (0x2F) precedes "0" (0x30); "\" (0x5C) would follow it.
expect(posix.map(({ path }) => path)).toEqual(["a", "a/b", "a0"]);
expect(windows.map(({ path }) => path)).toEqual(["a", "a/b", "a0"]);
expect(windows.map(({ listed }) => listed)).toEqual([
"\\a",
"\\a\\b",
"\\a0",
]);
});
it("keeps POSIX backslashes as literal filename characters", () => {
expect(orderAsarListing(["/a\\b"], "/")).toEqual([
{ listed: "/a\\b", path: "a\\b" },
]);
});
});
+28 -12
View File
@@ -32,6 +32,7 @@ import { closeAsarHandle, readValidatedAsarEntry } from "./AsarEntryStream.js";
import { admitAsarHeader } from "./AsarHeader.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import { readFileHandleChunks } from "../filesystem/readFileHandleChunks.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
/**
* Official Electron ASAR adapter with range-streamed member reads.
@@ -64,7 +65,7 @@ export class AsarArtifactReader implements ArtifactReader {
) {}
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
let paths: string[];
let paths: readonly AsarListedPath[];
try {
await this.prepareContainer(undefined, signal);
const snapshotPath = this.#snapshotPath();
@@ -82,9 +83,7 @@ export class AsarArtifactReader implements ArtifactReader {
await headerHandle.close();
}
abortIfNeeded(signal);
paths = listPackage(snapshotPath, { isPack: false }).sort((left, right) =>
left.localeCompare(right, "en"),
);
paths = orderAsarListing(listPackage(snapshotPath, { isPack: false }));
const archiveMetadata = await lstat(snapshotPath);
if (!archiveMetadata.isFile() || archiveMetadata.isSymbolicLink())
throw new ArtifactReaderFailure(
@@ -95,13 +94,8 @@ export class AsarArtifactReader implements ArtifactReader {
} catch (cause: unknown) {
throw asarFailure(this.path, "inventory", cause);
}
for (const listed of paths) {
for (const { listed, path } of paths) {
abortIfNeeded(signal);
// @electron/asar returns paths assembled with the host path module.
// Keep that spelling for its API calls, but expose archive paths with
// portable separators. On POSIX, backslashes can be literal filename
// characters and must remain untouched.
const path = toArtifactPath(listed);
if (path.length === 0) continue;
const providerPath = listed.startsWith(sep)
? listed.slice(sep.length)
@@ -577,8 +571,30 @@ const waitForOperation = async (
});
};
const toArtifactPath = (listed: string): string => {
const portable = sep === "\\" ? listed.replaceAll("\\", "/") : listed;
interface AsarListedPath {
readonly listed: string;
readonly path: string;
}
/**
* Pair each host-spelled listing with its portable archive path, ordered by
* the portable path so Windows and POSIX hosts agree.
*
* @electron/asar returns paths assembled with the host path module. Keep that
* spelling for its API calls, but expose archive paths with portable
* separators. On POSIX, backslashes can be literal filename characters and
* must remain untouched.
*/
export const orderAsarListing = (
listed: readonly string[],
separator: string = sep,
): AsarListedPath[] =>
listed
.map((entry) => ({ listed: entry, path: toArtifactPath(entry, separator) }))
.sort((left, right) => compareUnicodeCodePoints(left.path, right.path));
const toArtifactPath = (listed: string, separator: string): string => {
const portable = separator === "\\" ? listed.replaceAll("\\", "/") : listed;
return portable.replace(/^\/+|\/+$/gu, "");
};
@@ -13,6 +13,16 @@ describe("hostExecutableMarking", () => {
expect(
hostExecutableMarking("C:\\scratch\\SETUP.CMD", file(0o444), "win32"),
).toBe(true);
for (const path of [
"tools/SETUP.EXE",
"run.Cmd",
"build.bat",
"legacy.com",
])
expect(hostExecutableMarking(path, file(0o666), "win32")).toBe(true);
expect(hostExecutableMarking("readonly.exe", file(0o444), "win32")).toBe(
true,
);
expect(
hostExecutableMarking("C:\\scratch\\library.dll", file(0o666), "win32"),
).toBe(false);
@@ -25,6 +35,11 @@ describe("hostExecutableMarking", () => {
).toBe(false);
});
it("does not treat other Windows filenames as executable even with execute bits", () => {
for (const path of ["notes.txt", "README", "archive.exe.bak"])
expect(hostExecutableMarking(path, file(0o777), "win32")).toBe(false);
});
it("keeps POSIX permission bits authoritative regardless of extension", () => {
expect(hostExecutableMarking("/scratch/tool", file(0o755), "linux")).toBe(
true,
+4 -1
View File
@@ -68,6 +68,7 @@ import { captureCdpScreenshot } from "./CdpScreenshot.js";
import { comparePngScreenshots } from "./PngVisualDiff.js";
import { CDP_BROWSER_PROVIDER_IDENTITY } from "./providerIdentities.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
const CLEANUP_DOMAINS = ["Network", "Debugger", "Runtime", "Page"] as const;
/** Passive browser observation through a selected user-owned CDP endpoint. */
@@ -408,7 +409,9 @@ const selectTargets = (
attached: target.attached,
});
}
allowed.sort((left, right) => left.target_id.localeCompare(right.target_id));
allowed.sort((left, right) =>
compareUnicodeCodePoints(left.target_id, right.target_id),
);
return {
allowed,
excluded: {
+2 -1
View File
@@ -12,6 +12,7 @@ import {
import { exclusionReasonForUrl } from "./CdpCaptureEventHelpers.js";
import type { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
import { createDocumentSvgAncestry, domSvgLink } from "./CdpCaptureDomSvg.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
export type CapturedResource = Omit<
WebPageInspection["resources"][number],
@@ -346,7 +347,7 @@ const accessibilityStates = (
if (state !== undefined) states.set(name, state);
}
return [...states]
.sort(([left], [right]) => left.localeCompare(right))
.sort(([left], [right]) => compareUnicodeCodePoints(left, right))
.map(([name, state]) => ({ name, value: state }));
};
+2 -1
View File
@@ -24,6 +24,7 @@ import {
import { captureElectronScripts } from "./CdpElectronScripts.js";
import { captureElectronWorkers } from "./CdpElectronWorkers.js";
import { authorizedElectronFile } from "./ElectronFileScope.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
interface ElectronContext {
readonly connection: CdpConnection;
@@ -300,7 +301,7 @@ const captureResources = async (
pending.push(...recordsValue(tree.childFrames));
}
return resources.sort((left, right) =>
left.resource_key.localeCompare(right.resource_key),
compareUnicodeCodePoints(left.resource_key, right.resource_key),
);
};
+2 -1
View File
@@ -30,6 +30,7 @@ import { inspectCdpElectronPage } from "./CdpElectronInspection.js";
import { authorizedElectronFile } from "./ElectronFileScope.js";
import { CDP_ELECTRON_PROVIDER_IDENTITY } from "./providerIdentities.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
/** Passive Electron provider for local file pages exposed by loopback CDP. */
export class CdpElectronProvider implements ElectronObservationPort {
identity(): ProviderIdentity {
@@ -73,7 +74,7 @@ export class CdpElectronProvider implements ElectronObservationPort {
});
}
allowed.sort((left, right) =>
left.target_id.localeCompare(right.target_id),
compareUnicodeCodePoints(left.target_id, right.target_id),
);
return ok(
electronTargetListSchema.parse({
+2 -1
View File
@@ -9,6 +9,7 @@ import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
import { requiredScriptSource } from "./CdpCaptureValues.js";
import type { ElectronScriptDraft } from "./CdpElectronScriptEvents.js";
import { authorizedElectronFile } from "./ElectronFileScope.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
interface ElectronScriptCaptureInput {
readonly connection: CdpConnection;
@@ -65,7 +66,7 @@ export const captureElectronScripts = async (
return {
total,
items: items.sort((left, right) =>
left.script_key.localeCompare(right.script_key),
compareUnicodeCodePoints(left.script_key, right.script_key),
),
};
};
+2 -1
View File
@@ -12,6 +12,7 @@ import {
import type { CdpEndpointTarget } from "./CdpEndpoint.js";
import { optionalCdpCommand } from "./CdpOptionalCommand.js";
import { authorizedElectronFile } from "./ElectronFileScope.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
/** Inventory local worker targets without attaching to them. */
export const captureElectronWorkers = async (input: {
@@ -70,7 +71,7 @@ export const captureElectronWorkers = async (input: {
});
}
return workers.sort((left, right) =>
left.target_id.localeCompare(right.target_id),
compareUnicodeCodePoints(left.target_id, right.target_id),
);
};
+8 -3
View File
@@ -13,6 +13,7 @@ import {
} from "./CdpCaptureValues.js";
import type { CaptureContext } from "./CdpPageCapture.js";
import type { WebSourceMapRequest } from "./WebSourceMapFetcher.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
export interface CapturedScripts {
readonly inventory: WebPageInspection["scripts"];
@@ -131,11 +132,15 @@ const keyAndBuildInventory = (
}));
keyed.sort(
(left, right) =>
left.base.localeCompare(right.base) ||
sourceDigest(left.item.source).localeCompare(
compareUnicodeCodePoints(left.base, right.base) ||
compareUnicodeCodePoints(
sourceDigest(left.item.source),
sourceDigest(right.item.source),
) ||
(left.item.frame_id ?? "").localeCompare(right.item.frame_id ?? ""),
compareUnicodeCodePoints(
left.item.frame_id ?? "",
right.item.frame_id ?? "",
),
);
const totals = new Map<string, number>();
for (const { base } of keyed) totals.set(base, (totals.get(base) ?? 0) + 1);
+5 -2
View File
@@ -7,7 +7,10 @@ import type {
} from "../domain/webMcpDiscovery.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { digestCanonicalValue } from "../domain/canonicalDigest.js";
import { compositeKey } from "../domain/unicodeCodePointOrder.js";
import {
compareUnicodeCodePoints,
compositeKey,
} from "../domain/unicodeCodePointOrder.js";
import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js";
import type { CdpConnection, CdpEvent } from "./CdpConnection.js";
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
@@ -521,7 +524,7 @@ const buildWebMcpResult = (options: WebMcpResultOptions): WebMcpDiscovery => {
tools: {
total: tools.size + completeness.droppedTotal,
items: [...tools.values()].sort((left, right) =>
left.tool_key.localeCompare(right.tool_key),
compareUnicodeCodePoints(left.tool_key, right.tool_key),
),
},
completeness: completeness.snapshot(),
+3 -2
View File
@@ -6,9 +6,10 @@ import { z } from "zod";
import { PROMPT_CONTRACTS } from "./contracts/promptContracts.js";
import { TOOL_CONTRACTS } from "./contracts/toolContracts.js";
import { CLI_COMMAND_NAMES } from "./cliCommandNames.js";
import { compareUnicodeCodePoints } from "./domain/unicodeCodePointOrder.js";
const sortedToolContracts = [...TOOL_CONTRACTS].sort((left, right) =>
left.name.localeCompare(right.name),
compareUnicodeCodePoints(left.name, right.name),
);
const createToolCatalog = () =>
@@ -39,7 +40,7 @@ const promptCatalog = PROMPT_CONTRACTS.map((contract) => ({
description: contract.description,
arguments: contract.arguments,
steps: contract.steps,
})).sort((left, right) => left.name.localeCompare(right.name));
})).sort((left, right) => compareUnicodeCodePoints(left.name, right.name));
const digest = (value: unknown): string => {
const encoded = canonicalize(value);
+156
View File
@@ -0,0 +1,156 @@
import { describe, expect, it } from "vitest";
import { TOOL_CONTRACTS } from "./toolContracts.js";
import { TOOL_EFFECTS, annotationsFromEffects } from "./toolEffects.js";
/**
* Descriptions that name running, launching, executing, starting, installing,
* or uninstalling something. A matching tool must declare foreign execution or
* device mutation unless it is listed below with the reason the wording does
* not describe that effect.
*/
const EXECUTION_WORDING =
/\b(?:run|runs|running|launch|launches|launching|execute|executes|executing|execution|start|starts|install|installs|uninstall|uninstalls)\b/iu;
const EXECUTION_WORDING_EXCEPTIONS: Readonly<Record<string, string>> = {
inspect_native_load_image: "states that it does not execute the target",
resolve_native_call_targets: "states that it does not execute code",
inspect_pe_resources: "states that it does not execute the image",
inspect_binary_layout:
"parses the binary offline with operator-configured pwntools",
inspect_recorded_crash: "inspects a core file without launching its target",
inspect_macho: "runs host Mach-O inspection tools, not the target",
inspect_evm_interface:
"decodes bytecode in REA's bundled worker without executing it",
inspect_managed_artifact: "reads metadata without executing target code",
inspect_managed_members: "reads metadata without executing target code",
inspect_managed_native_boundaries:
"reads metadata without executing target code",
verify_managed_native_boundaries: "states it does not execute managed code",
project_managed_application_graph: "states it does not execute managed code",
inspect_android_package: "states it does not execute the APK",
search_android_classes: "states it does not execute the APK",
inspect_apktool_client:
"inspects the operator-selected apktool launcher; never installs it",
inspect_jeb_client: "talks to a caller-started JEB; never launches it",
open_jeb_project: "the engine analyzes the file; REA does not execute it",
inspect_adb_client:
"inspects the operator-selected adb client; never starts its server",
list_adb_devices: "may start the local adb server, which REA does not own",
inspect_firmware_regions: "states there is no target execution",
extract_firmware: "states that extracted code is never executed",
analyze_javascript_application: "reconstructs the graph without executing",
reconcile_javascript_runtime: "never invents execution claims",
observe_javascript_runtime: "never evaluates or resumes the target",
trace_application_feature: "never executes the application",
trace_javascript_semantics: "static reachability never claims execution",
compare_javascript_export_shapes: "states it does not execute JavaScript",
project_android_application_graph: "execution-free inventory",
project_apple_application_graph: "execution-free inventory",
trace_web_source_location: "states there is no application execution",
trace_web_module_imports:
"runs only REA's resolver stub in operator-configured Chromium",
export_web_scripts: "states there is no refetch or execution",
observe_web_execution:
"instruments an externally driven page; it does not run code itself",
recover_javascript_sources: "states there is no application code execution",
goto_address: "start names an object boundary, not a launch",
prev_address: "start names an object boundary, not a launch",
trace_call_path: "start names the traversal origin",
observe_native_ui: "observes an already-running app without launching it",
inspect_adb_package: "reports install times without changing the device",
list_adb_processes: "lists running processes without changing the device",
inspect_web_event_listeners: "states it does not evaluate JavaScript",
};
const declaresForeignAuthority = (name: string): boolean => {
const effects = TOOL_EFFECTS[name];
return (
effects !== undefined &&
(effects.executesForeignCode || effects.mutatesDevice)
);
};
describe("tool effects", () => {
it("audits every public tool exactly once", () => {
expect(Object.keys(TOOL_EFFECTS).sort()).toEqual(
TOOL_CONTRACTS.map(({ name }) => name).sort(),
);
});
it("keeps execution and device wording aligned with declared effects", () => {
const undeclared = TOOL_CONTRACTS.filter(
({ name, description }) =>
EXECUTION_WORDING.test(description) &&
!declaresForeignAuthority(name) &&
EXECUTION_WORDING_EXCEPTIONS[name] === undefined,
).map(({ name }) => name);
expect(undeclared).toEqual([]);
const staleExceptions = Object.keys(EXECUTION_WORDING_EXCEPTIONS).filter(
(name) => {
const contract = TOOL_CONTRACTS.find(
(candidate) => candidate.name === name,
);
return (
contract === undefined ||
!EXECUTION_WORDING.test(contract.description) ||
declaresForeignAuthority(name)
);
},
);
expect(staleExceptions).toEqual([]);
});
it("marks foreign execution and device mutation as destructive", () => {
const destructive = TOOL_CONTRACTS.filter(
({ effects }) => effects.executesForeignCode || effects.mutatesDevice,
);
expect(destructive.map(({ name }) => name).sort()).toEqual([
"capture_browser_scenario",
"capture_electron_scenario",
"capture_native_ui_scenario",
"capture_process_scenario",
"install_adb_package",
"observe_native_calls",
"push_adb_file",
"start_adb_activity",
"start_adb_app",
"stop_adb_app",
"uninstall_adb_package",
]);
for (const contract of destructive)
expect(contract.annotations, contract.name).toMatchObject({
readOnlyHint: false,
destructiveHint: true,
});
});
it("derives destructiveHint from each destructive effect alone", () => {
const base = TOOL_EFFECTS["binary_session"];
if (base === undefined) throw new Error("binary_session is unaudited");
expect(annotationsFromEffects(base)).toEqual({
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
});
for (const flag of [
"mayDiscardData",
"executesForeignCode",
"mutatesDevice",
] as const)
expect(annotationsFromEffects({ ...base, [flag]: true }), flag).toEqual({
readOnlyHint: false,
destructiveHint: true,
idempotentHint: true,
openWorldHint: false,
});
});
it("publishes the advertised annotations derived from canonical effects", () => {
for (const contract of TOOL_CONTRACTS)
expect(contract.annotations, contract.name).toEqual(
annotationsFromEffects(contract.effects),
);
});
});
+57 -7
View File
@@ -7,7 +7,17 @@ export interface ToolEffects {
readonly launchesProcess: boolean;
readonly accessesNetwork: boolean;
readonly changesUiState: boolean;
/** Can overwrite, clear, or drop state that the caller cannot recover from REA. */
readonly mayDiscardData: boolean;
/**
* Runs or drives code REA does not own on the host: the analysis target, a
* caller-selected executable, or the application loaded into one. Running
* REA's own pinned helpers or operator-configured analysis engines does not
* count.
*/
readonly executesForeignCode: boolean;
/** Changes an attached Android device: packages, files, or running apps. */
readonly mutatesDevice: boolean;
readonly idempotent: boolean;
}
@@ -27,6 +37,8 @@ const effects = (overrides: Partial<ToolEffects> = {}): ToolEffects => ({
accessesNetwork: false,
changesUiState: false,
mayDiscardData: false,
executesForeignCode: false,
mutatesDevice: false,
idempotent: true,
...overrides,
});
@@ -178,6 +190,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
launchesProcess: true,
writesFilesystem: true,
accessesNetwork: true,
mutatesDevice: true,
idempotent: false,
}),
capture_adb_screen: effects({
@@ -239,6 +252,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
mutatesSession: true,
launchesProcess: true,
accessesNetwork: true,
mutatesDevice: true,
idempotent: false,
}),
uninstall_adb_package: effects({
@@ -246,6 +260,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
mutatesSession: true,
launchesProcess: true,
accessesNetwork: true,
mutatesDevice: true,
idempotent: false,
}),
start_adb_app: effects({
@@ -253,6 +268,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
mutatesSession: true,
launchesProcess: true,
accessesNetwork: true,
mutatesDevice: true,
idempotent: false,
}),
start_adb_activity: effects({
@@ -260,6 +276,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
mutatesSession: true,
launchesProcess: true,
accessesNetwork: true,
mutatesDevice: true,
idempotent: false,
}),
stop_adb_app: effects({
@@ -267,6 +284,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
mutatesSession: true,
launchesProcess: true,
accessesNetwork: true,
mutatesDevice: true,
idempotent: false,
}),
search_android_classes: effects({
@@ -294,6 +312,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
mutatesSession: true,
launchesProcess: true,
writesFilesystem: true,
mayDiscardData: true,
}),
inspect_native_load_image: evidence,
inspect_native_dispatch_metadata: evidence,
@@ -330,11 +349,31 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
resolve_containing_procedure: evidence,
search_procedures: evidence,
search_strings: evidence,
set_address_name: effects({ mutatesTarget: true, mutatesSession: true }),
set_addresses_names: effects({ mutatesTarget: true, mutatesSession: true }),
set_bookmark: effects({ mutatesTarget: true, mutatesSession: true }),
set_comment: effects({ mutatesTarget: true, mutatesSession: true }),
set_inline_comment: effects({ mutatesTarget: true, mutatesSession: true }),
set_address_name: effects({
mutatesTarget: true,
mutatesSession: true,
mayDiscardData: true,
}),
set_addresses_names: effects({
mutatesTarget: true,
mutatesSession: true,
mayDiscardData: true,
}),
set_bookmark: effects({
mutatesTarget: true,
mutatesSession: true,
mayDiscardData: true,
}),
set_comment: effects({
mutatesTarget: true,
mutatesSession: true,
mayDiscardData: true,
}),
set_inline_comment: effects({
mutatesTarget: true,
mutatesSession: true,
mayDiscardData: true,
}),
unset_bookmark: effects({
mutatesTarget: true,
mutatesSession: true,
@@ -365,6 +404,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
accessesNetwork: true,
changesUiState: true,
mayDiscardData: true,
executesForeignCode: true,
idempotent: false,
}),
// The owned process can change files, show UI and use the network.
@@ -374,6 +414,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
launchesProcess: true,
accessesNetwork: true,
changesUiState: true,
executesForeignCode: true,
idempotent: false,
}),
inspect_macho: nativeEvidence,
@@ -419,6 +460,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
accessesNetwork: true,
changesUiState: true,
mayDiscardData: true,
executesForeignCode: true,
idempotent: false,
}),
list_electron_targets: browserEvidence,
@@ -431,6 +473,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
accessesNetwork: true,
changesUiState: true,
mayDiscardData: true,
executesForeignCode: true,
idempotent: false,
}),
list_javascript_runtime_targets: browserEvidence,
@@ -479,6 +522,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
writesFilesystem: true,
launchesProcess: true,
accessesNetwork: true,
executesForeignCode: true,
idempotent: false,
}),
compare_process_captures: sessionEvidence,
@@ -506,9 +550,15 @@ export const annotationsFromEffects = (
value.launchesProcess ||
value.accessesNetwork ||
value.changesUiState ||
value.mayDiscardData
value.mayDiscardData ||
value.executesForeignCode ||
value.mutatesDevice
),
destructiveHint: value.mayDiscardData,
// MCP defines destructive as possibly non-additive changes to the
// environment. Running foreign code or changing a device cannot be bounded
// to additive effects, so either one is destructive even without data loss.
destructiveHint:
value.mayDiscardData || value.executesForeignCode || value.mutatesDevice,
idempotentHint: value.idempotent,
openWorldHint: value.launchesProcess || value.accessesNetwork,
});
@@ -293,6 +293,8 @@ const toolAvailabilityFacts = {
accessesNetwork: z.boolean(),
changesUiState: z.boolean(),
mayDiscardData: z.boolean(),
executesForeignCode: z.boolean(),
mutatesDevice: z.boolean(),
idempotent: z.boolean(),
}),
annotations: z.object({
@@ -0,0 +1,84 @@
import { describe, expect, it } from "vitest";
import { ROLLDOWN_MODULE_INTEROP } from "./javascriptModuleInterop.fixture.js";
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
const CAPTURED_INTEROP = ROLLDOWN_MODULE_INTEROP.replace(
"__defProp = Object.defineProperty",
"__defProp = define",
);
const WINDOW = `let electron = require("electron");
electron = __toESM(electron, 1); new electron.BrowserWindow({});`;
describe("captured intrinsic invocation reads", () => {
it.each([
'(0, Object.defineProperty.call)(null,Object,"create",{value:replacement});',
'(0, Object.defineProperty.apply)(null,[Object,"create",{value:replacement}]);',
])(
"does not invent a receiver for a detached invocation member: %s",
(invoke) => {
const result = analyzeJavaScriptStaticSource(`
${invoke}
${ROLLDOWN_MODULE_INTEROP} ${WINDOW}
`);
expect(result.electron.browser_windows).toHaveLength(1);
},
);
it("retains callee-prefix effects before classifying the invocation", () => {
const result = analyzeJavaScriptStaticSource(`
const define = Object.defineProperty;
const metadata = {};
(Object.defineProperty = replacement, Object.defineProperty)(metadata,"x",{value:1});
${CAPTURED_INTEROP} ${WINDOW}
`);
expect(result.electron.browser_windows).toEqual([]);
});
it("retains a callee selected before an argument replaces its global property", () => {
const result = analyzeJavaScriptStaticSource(`
const define = Object.defineProperty;
const metadata = {};
Object.defineProperty(metadata,"x",(Object.defineProperty = replacement,{value:1}));
${CAPTURED_INTEROP} ${WINDOW}
`);
expect(result.electron.browser_windows).toHaveLength(1);
});
it.each([
'define.call(null,metadata,"x",{value:1});',
'define.apply(null,[metadata,"x",{value:1}]);',
'const change = define.bind(null,metadata,"x"); change({value:1});',
'const also = define; also.call(null,metadata,"x",{value:1});',
])("retains a function captured before global replacement: %s", (invoke) => {
const result = analyzeJavaScriptStaticSource(`
const define = Object.defineProperty;
Object.defineProperty = replacement;
const metadata = {}; ${invoke}
${CAPTURED_INTEROP} ${WINDOW}
`);
expect(result.electron.browser_windows).toHaveLength(1);
});
it.each([
["call", 'define.call(null,metadata,"x",{value:1});'],
["apply", 'define.apply(null,[metadata,"x",{value:1}]);'],
[
"bind",
'const change = define.bind(null,metadata,"x"); change({value:1});',
],
])(
"checks the later %s property read on a captured function",
(method, invoke) => {
for (const owner of ["define", "Function.prototype"]) {
const result = analyzeJavaScriptStaticSource(`
const define = Object.defineProperty;
${owner}.${method} = replacement;
const metadata = {}; ${invoke}
${CAPTURED_INTEROP} ${WINDOW}
`);
expect(result.electron.browser_windows, owner).toEqual([]);
}
},
);
});
@@ -539,11 +539,9 @@ describe("Electron module interop generic invocations", () => {
'const change = Function.prototype.call.bind(Object.defineProperty); change(null,Object,"create",{value:customCreate});',
'const call = Function.prototype.call; const change = call.bind(Object.defineProperty); change(null,Object,"create",{value:customCreate});',
'const change = Function.prototype.call.bind(Object.defineProperty,null,Object,"create"); change({value:customCreate});',
'Function.prototype.call.call(Object.defineProperty,null,Object,"create",{value:customCreate});',
'Function.prototype.call.apply(Object.defineProperty,[null,Object,"create",{value:customCreate}]);',
'Reflect.apply(Function.prototype.call,Object.defineProperty,[null,Object,"create",{value:customCreate}]);',
'const change = Function.prototype.apply.bind(Object.defineProperty); change(null,[Object,"create",{value:customCreate}]);',
'Function.prototype.apply.call(Object.defineProperty,null,[Object,"create",{value:customCreate}]);',
'Reflect.apply(Function.prototype.apply,Object.defineProperty,[null,[Object,"create",{value:customCreate}]]);',
'const first = Function.prototype.call.bind(Object.defineProperty,null,Object,"create"); const change = first.bind(fake); change({value:customCreate});',
"const change = Function.prototype.call.bind(Object.defineProperty); change(null,...args);",
@@ -617,6 +615,10 @@ describe("Electron module interop bound mutators", () => {
'Reflect.set({},"create",...valuesAndReceivers);',
"Reflect.set({},...keysValuesAndReceivers);",
'Reflect.set({},"create",customCreate,receiver);',
'(0, Object.defineProperty)(Object,"create",{value:customCreate});',
'const change = Object.defineProperty.bind(null,Object,"create"); (0, change)({value:customCreate});',
'(0, Reflect.apply)(Object.defineProperty,null,[Object,"create",{value:customCreate}]);',
'Reflect.apply((0,Function.prototype.call),Object.defineProperty,[null,Object,"create",{value:customCreate}]);',
])("rejects intrinsic writes through a bound mutator: %s", (write) => {
expect(
analyzeJavaScriptStaticSource(
@@ -643,6 +645,7 @@ describe("Electron module interop bound mutators", () => {
'const {apply:change} = Object.defineProperty; change.call(Object.defineProperty,null,[metadata,"x",{value:1}]);',
'Reflect.set(metadata,"x",1,{});',
'const receiver = {}; Reflect.set({},"x",1,receiver);',
'(0, Object.defineProperty)(metadata,"x",{value:1});',
])("keeps a fresh bound target or unused binding separate: %s", (write) => {
expect(
analyzeJavaScriptStaticSource(
@@ -79,60 +79,60 @@ export function* collectJavaScriptIdentityWritesSteps(
"setPrototypeOf",
]);
const keyedMutators = new Set(["set", "deleteProperty", "defineProperty"]);
yield* traverseJavaScriptAstSteps(program, {
enter: (node) => {
if (t.isCallExpression(node) || t.isOptionalCallExpression(node)) {
const invocation = intrinsicInvocation(node);
if (invocation?.kind === "opaque") {
const retainCallEffects = (
node: t.CallExpression | t.OptionalCallExpression,
): void => {
const invocation = intrinsicInvocation(node);
if (invocation?.kind === "opaque") {
const scope = origin(node, "opaque-call");
if (scope !== undefined) retain(node, scope);
return;
}
const callee = invocation?.path;
const arguments_ = invocation?.arguments;
const method = callee?.at(-1);
const owner = callee?.length === 3 ? callee[1] : undefined;
if (
(owner === "Object" && objectMutators.has(method ?? "")) ||
(owner === "Reflect" && reflectMutators.has(method ?? ""))
) {
// Reflect.set can write through its explicit receiver as well as
// dispatching through its target. Both identities need examination.
const targets =
owner === "Reflect" &&
method === "set" &&
arguments_ !== undefined &&
(arguments_.length >= 4 || arguments_.some(t.isSpreadElement))
? [
arguments_[0],
arguments_.some(t.isSpreadElement) ? undefined : arguments_[3],
]
: [arguments_?.[0]];
for (const target of targets) {
// A known mutator with an opaque argument list can overwrite any
// captured intrinsic. Do not turn an unexamined target into proof.
if (target === undefined || t.isSpreadElement(target)) {
const scope = origin(node, "opaque-call");
if (scope !== undefined) retain(node, scope);
return;
}
const callee = invocation?.path;
const arguments_ = invocation?.arguments;
const method = callee?.at(-1);
const owner = callee?.length === 3 ? callee[1] : undefined;
if (
(owner === "Object" && objectMutators.has(method ?? "")) ||
(owner === "Reflect" && reflectMutators.has(method ?? ""))
) {
// Reflect.set can write through its explicit receiver as well as
// dispatching through its target. Both identities need examination.
const targets =
owner === "Reflect" &&
method === "set" &&
arguments_ !== undefined &&
(arguments_.length >= 4 || arguments_.some(t.isSpreadElement))
? [
arguments_[0],
arguments_.some(t.isSpreadElement)
? undefined
: arguments_[3],
]
: [arguments_?.[0]];
for (const target of targets) {
// A known mutator with an opaque argument list can overwrite any
// captured intrinsic. Do not turn an unexamined target into proof.
if (target === undefined || t.isSpreadElement(target)) {
const scope = origin(node, "opaque-call");
if (scope !== undefined) retain(node, scope);
}
if (t.isNode(target) && !t.isSpreadElement(target)) {
const { root, members } = electronMemberPath(target);
const exported = origin(root, "member");
if (exported !== undefined) {
const key = keyedMutators.has(method ?? "")
? [staticString(arguments_?.[1]) ?? null]
: [];
retain(node, [...exported, ...members, ...key]);
} else if (!freshObject(target)) {
const scope = origin(node, "opaque-call");
if (scope !== undefined) retain(node, scope);
}
}
if (t.isNode(target) && !t.isSpreadElement(target)) {
const { root, members } = electronMemberPath(target);
const exported = origin(root, "member");
if (exported !== undefined) {
const key = keyedMutators.has(method ?? "")
? [staticString(arguments_?.[1]) ?? null]
: [];
retain(node, [...exported, ...members, ...key]);
} else if (!freshObject(target)) {
const scope = origin(node, "opaque-call");
if (scope !== undefined) retain(node, scope);
}
}
}
}
};
yield* traverseJavaScriptAstSteps(program, {
enter: (node) => {
const target = t.isAssignmentExpression(node)
? node.left
: t.isUpdateExpression(node)
@@ -154,5 +154,9 @@ export function* collectJavaScriptIdentityWritesSteps(
if (exported !== undefined) retain(node, [...exported, ...members]);
}
},
exit: (node) => {
if (t.isCallExpression(node) || t.isOptionalCallExpression(node))
retainCallEffects(node);
},
});
}
@@ -41,6 +41,15 @@ export const resolveJavaScriptIntrinsicInvocation = (
let explicitReceiver = false;
for (;;) {
callee = unwrapJavaScriptExpression(callee).node;
if (t.isSequenceExpression(callee)) {
const finalExpression = callee.expressions.at(-1);
if (finalExpression === undefined) return undefined;
// Comma yields a value, not a member reference. An outer invocation
// can still supply an explicit receiver for that value.
explicitReceiver = true;
callee = finalExpression;
continue;
}
if (visited.has(callee)) return undefined;
visited.add(callee);
let path = intrinsicPath(callee);
@@ -20,7 +20,7 @@ import {
type JavaScriptIntrinsicInvocation,
} from "./javascriptElectronMemberWrites.js";
import { resolveJavaScriptIntrinsicInvocation } from "./javascriptIntrinsicInvocation.js";
import { SemanticPropertyPathCoverage } from "./javascriptSemanticPropertyPaths.js";
import { semanticPropertyPathKeyMatches } from "./javascriptSemanticPropertyPaths.js";
import {
readExactJavaScriptLiteral,
unwrapJavaScriptExpression,
@@ -71,6 +71,16 @@ interface InteropHelper {
readonly identity: boolean;
}
const intrinsicWriteCovers = (
written: readonly (string | null)[],
read: readonly string[],
): boolean =>
written.length <= read.length &&
written.every((key, index) => {
const name = read[index];
return name !== undefined && semanticPropertyPathKeyMatches(key, name);
});
/** Prove one inert namespace conversion without relaxing general assignment semantics. */
export const createSemanticModuleInterop = (
state: JavaScriptSemanticAnalysisState,
@@ -82,7 +92,7 @@ export const createSemanticModuleInterop = (
const writes: {
readonly scope: string;
readonly offset: number;
readonly coverage: SemanticPropertyPathCoverage;
readonly path: readonly (string | null)[];
}[] = [];
const invalidatedBindings = new Map<string, boolean>();
const invalidatedCalls = new WeakMap<t.Node, boolean>();
@@ -117,6 +127,12 @@ export const createSemanticModuleInterop = (
const { root, members } = electronMemberPath(current);
if (members.some((member) => member === null)) return finish(undefined);
suffix = [...(members as readonly string[]), ...suffix];
if (t.isSequenceExpression(root)) {
const value = root.expressions.at(-1);
if (value === undefined) return finish(undefined);
current = value;
continue;
}
for (const global of ["Object", "Function", "Reflect"])
if (isUnshadowedGlobal(root, state, global))
return finish(["intrinsic", global, ...suffix]);
@@ -157,8 +173,20 @@ export const createSemanticModuleInterop = (
let capturedAt = node;
let suffixLength = 0;
for (;;) {
current = unwrapJavaScriptExpression(current).node;
if (suffixLength === 0)
capturedAt =
t.isMemberExpression(current) || t.isOptionalMemberExpression(current)
? current.property
: current;
const { root, members } = electronMemberPath(current);
suffixLength += members.length;
if (t.isSequenceExpression(root)) {
const value = root.expressions.at(-1);
if (value === undefined) return undefined;
current = value;
continue;
}
if (!t.isIdentifier(root)) return undefined;
const binding = resolveSemanticBindingState(state, root, root.name);
if (binding === undefined) return { path, capturedAt };
@@ -209,24 +237,56 @@ export const createSemanticModuleInterop = (
node: t.Node,
path: readonly string[],
): boolean => {
const capture = capturedIntrinsic(node)?.capturedAt ?? node;
const scope = opaqueMutationPath(capture).join(".");
const method = path.at(-1);
const invocationMethod =
method === "bind" || method === "call" || method === "apply";
return writes.some(
(write) =>
(write.scope === scope || write.scope === "intrinsic") &&
write.offset < (capture.start ?? -1) &&
(write.coverage.covers(path) ||
(invocationMethod &&
write.coverage.covers([
"intrinsic",
"Function",
"prototype",
method,
]))),
);
let current = unwrapJavaScriptExpression(node).node;
let currentPath = path;
for (;;) {
const method = currentPath.at(-1);
const invocationMethod =
method === "bind" || method === "call" || method === "apply";
if (
invocationMethod &&
(t.isMemberExpression(current) || t.isOptionalMemberExpression(current))
) {
// Reading an invocation member does not recapture the stored function.
// Check member writes now, then check its base at the earlier capture.
const scope = opaqueMutationPath(current).join(".");
const offset = current.property.start ?? -1;
if (
writes.some(
(write) =>
(write.scope === scope || write.scope === "intrinsic") &&
write.offset < offset &&
((write.path.length >= currentPath.length &&
intrinsicWriteCovers(write.path, currentPath)) ||
intrinsicWriteCovers(write.path, [
"intrinsic",
"Function",
"prototype",
method,
])),
)
)
return true;
current = unwrapJavaScriptExpression(current.object).node;
currentPath = currentPath.slice(0, -1);
continue;
}
const capture = capturedIntrinsic(current)?.capturedAt ?? current;
const scope = opaqueMutationPath(capture).join(".");
return writes.some(
(write) =>
(write.scope === scope || write.scope === "intrinsic") &&
write.offset < (capture.start ?? -1) &&
(intrinsicWriteCovers(write.path, currentPath) ||
(invocationMethod &&
intrinsicWriteCovers(write.path, [
"intrinsic",
"Function",
"prototype",
method,
]))),
);
}
};
const resolveBoundIntrinsic = (
@@ -270,7 +330,7 @@ export const createSemanticModuleInterop = (
if (members.at(-1) === "bind") {
// A direct .bind may continue a bound callable, without discarding members.
if (!terminal && members.length !== 1) return undefined;
bindReads.push(captured?.capturedAt ?? current.callee);
bindReads.push(current.callee);
} else {
// Reuse the invocation owner for generic call/apply/Reflect.apply of bind.
const invocation = resolveJavaScriptIntrinsicInvocation(
@@ -290,6 +350,8 @@ export const createSemanticModuleInterop = (
captured = capturedIntrinsic(bindTarget);
terminal = captured !== undefined;
path = captured?.path;
opaqueArguments ||=
path !== undefined && intrinsicReadChanged(bindTarget, path);
}
receiver = bindingArguments?.[0];
const ownArguments = bindingArguments?.slice(1) ?? [];
@@ -304,17 +366,9 @@ export const createSemanticModuleInterop = (
continue;
}
const boundPath = [...path, "bind"];
const functionBind = ["intrinsic", "Function", "prototype", "bind"];
opaqueArguments ||= bindReads.some((capture) => {
const scope = opaqueMutationPath(capture).join(".");
return writes.some(
(write) =>
(write.scope === scope || write.scope === "intrinsic") &&
write.offset < (capture.start ?? -1) &&
(write.coverage.covers(boundPath) ||
write.coverage.covers(functionBind)),
);
});
opaqueArguments ||= bindReads.some((capture) =>
intrinsicReadChanged(capture, boundPath),
);
return {
kind: opaqueArguments ? "opaque" : "known",
path,
@@ -602,7 +656,7 @@ export const createSemanticModuleInterop = (
(write) =>
(write.scope === scope || write.scope === "intrinsic") &&
write.offset < (capturedAt.start ?? -1) &&
write.coverage.covers(path),
intrinsicWriteCovers(write.path, path),
);
}) ?? false;
return {
@@ -621,12 +675,10 @@ export const createSemanticModuleInterop = (
isFreshObject,
opaqueMutationPath,
retainWrite: (node: t.Node, path: readonly (string | null)[]) => {
const coverage = new SemanticPropertyPathCoverage();
coverage.retain(path[0] === "opaque-intrinsic" ? ["intrinsic"] : path);
writes.push({
scope: opaqueMutationPath(node).join("."),
offset: node.start ?? Infinity,
coverage,
path: path[0] === "opaque-intrinsic" ? ["intrinsic"] : path,
});
},
invalidated: (binding: JavaScriptSemanticBindingState): boolean => {
@@ -0,0 +1,147 @@
import { describe, expect, it } from "vitest";
import {
classifyPackageImportSpecifier,
classifyPackageImportTargetString,
lookupExactPackageImport,
} from "./javascriptPackageImportAliases.js";
describe("package import specifier classification", () => {
it("treats an exact hash alias as an exact key", () => {
expect(classifyPackageImportSpecifier("#config")).toEqual({
kind: "exact",
key: "#config",
});
});
it.each(["#internal/env", "#/hidden"])(
"treats %j as an exact key",
(specifier) => {
expect(classifyPackageImportSpecifier(specifier)).toEqual({
kind: "exact",
key: specifier,
});
},
);
it.each(["#", "#/", "#utils/"])(
"rejects reserved specifier %j",
(specifier) => {
expect(classifyPackageImportSpecifier(specifier)).toEqual({
kind: "invalid",
});
},
);
it.each(["#internal/*", "#*"])(
"leaves pattern specifier %j unresolved",
(specifier) => {
expect(classifyPackageImportSpecifier(specifier)).toEqual({
kind: "pattern",
});
},
);
});
describe("exact package import lookup", () => {
it("returns the exact target without falling through to another key", () => {
expect(
lookupExactPackageImport(
{ "#config": "./config.cjs", "#other": "./other.cjs" },
"#config",
),
).toEqual({
kind: "found",
target: "./config.cjs",
declared: ["#config", "#other"],
});
});
it("names declared exact keys when the requested alias is absent", () => {
expect(
lookupExactPackageImport({ "#config": "./config.cjs" }, "#missing"),
).toEqual({
kind: "missing-key",
declared: ["#config"],
});
});
it("does not claim a miss when the map only has pattern keys", () => {
expect(
lookupExactPackageImport({ "#internal/*": "./src/*.js" }, "#internal/a"),
).toEqual({
kind: "pattern-unresolved",
declared: ["#internal/*"],
});
});
it("still selects an exact key when the same map also has patterns", () => {
expect(
lookupExactPackageImport(
{ "#config": "./config.cjs", "#internal/*": "./src/*.js" },
"#config",
),
).toEqual({
kind: "found",
target: "./config.cjs",
declared: ["#config", "#internal/*"],
});
});
it.each([undefined, null, "./config.cjs", ["#config"], 7] as const)(
"treats non-object imports value %j as an undefined map",
(imports) => {
expect(lookupExactPackageImport(imports, "#config")).toEqual({
kind: "undefined-map",
});
},
);
it("does not treat a pattern key as an exact match for itself", () => {
expect(
lookupExactPackageImport({ "#internal/*": "./src/*.js" }, "#internal/*"),
).toEqual({
kind: "pattern-unresolved",
declared: ["#internal/*"],
});
});
});
describe("package import target string classification", () => {
it("keeps package-local relative targets", () => {
expect(classifyPackageImportTargetString("./config.cjs")).toEqual({
kind: "relative",
target: "./config.cjs",
});
});
it("marks recursive hash aliases as recursive", () => {
expect(classifyPackageImportTargetString("#other")).toEqual({
kind: "recursive",
target: "#other",
});
});
it.each(["lodash", "pkg/subpath"])(
"marks %j as an external-package target",
(target) => {
expect(classifyPackageImportTargetString(target)).toEqual({
kind: "external-package",
target,
});
},
);
it.each([
"../outside.js",
"/outside.js",
"https://example.invalid/mod.js",
"file:///outside.js",
"node:fs",
])("marks %j as an invalid import target", (target) => {
expect(classifyPackageImportTargetString(target)).toEqual({
kind: "invalid",
target,
});
});
});
@@ -0,0 +1,98 @@
/**
* Exact package-private import-alias lookup. Node resolves `#` specifiers
* against the importer's enclosing package `imports` map; this module owns the
* specifier and exact-key rules. Condition, array, and null target selection
* stay with the shared package-target machinery. Wildcard keys, recursive
* `#` targets, and external-package targets remain explicit unknowns.
*/
/** How one `#` specifier participates in exact import-alias lookup. */
export type PackageImportSpecifierClassification =
| { readonly kind: "invalid" }
| { readonly kind: "pattern" }
| { readonly kind: "exact"; readonly key: string };
/** Outcome of looking up one exact `#` key in a package `imports` object. */
export type PackageImportExactLookup =
| { readonly kind: "undefined-map" }
| {
readonly kind: "missing-key";
readonly declared: readonly string[];
}
| {
readonly kind: "pattern-unresolved";
readonly declared: readonly string[];
}
| {
readonly kind: "found";
readonly target: unknown;
readonly declared: readonly string[];
};
/** How a selected string target is interpreted for package-private imports. */
export type PackageImportTargetClassification =
| { readonly kind: "relative"; readonly target: string }
| { readonly kind: "invalid"; readonly target: string }
| { readonly kind: "recursive"; readonly target: string }
| { readonly kind: "external-package"; readonly target: string };
/**
* Classify a `#` module specifier before any package-scope walk.
* `#` and names ending in `/` are invalid. Other literal keys, including
* `#/…`, participate in exact lookup; wildcard expansion remains unsupported.
*/
export const classifyPackageImportSpecifier = (
specifier: string,
): PackageImportSpecifierClassification => {
if (specifier === "#" || specifier.endsWith("/")) return { kind: "invalid" };
if (specifier.includes("*")) return { kind: "pattern" };
return { kind: "exact", key: specifier };
};
/** True when an `imports` key is a pattern rather than an exact alias. */
export const isPackageImportPatternKey = (key: string): boolean =>
key.includes("*") || key.endsWith("/");
/**
* Look up one exact `#` key in a package `imports` value.
* A missing exact key is reported as missing when every declared key is also
* exact; if the map contains pattern keys, the miss stays pattern-unresolved
* rather than claiming the specifier is undefined.
*/
export const lookupExactPackageImport = (
imports: unknown,
key: string,
): PackageImportExactLookup => {
if (typeof imports !== "object" || imports === null || Array.isArray(imports))
return { kind: "undefined-map" };
const declared = Object.keys(imports);
if (Object.hasOwn(imports, key) && !isPackageImportPatternKey(key))
return {
kind: "found",
target: Reflect.get(imports, key),
declared,
};
return declared.some(isPackageImportPatternKey)
? { kind: "pattern-unresolved", declared }
: { kind: "missing-key", declared };
};
/**
* Classify a selected string import target. Only package-local `./` paths are
* resolved as files; recursive `#` aliases and bare packages stay unknown.
* Parent-relative, absolute, and URL targets are invalid, allowing array
* selection to skip them before choosing a package-local fallback.
*/
export const classifyPackageImportTargetString = (
target: string,
): PackageImportTargetClassification => {
if (target.startsWith("./")) return { kind: "relative", target };
if (
target.startsWith("../") ||
target.startsWith("/") ||
URL.canParse(target)
)
return { kind: "invalid", target };
if (target.startsWith("#")) return { kind: "recursive", target };
return { kind: "external-package", target };
};
@@ -179,6 +179,34 @@ describe("JavaScript semantic analysis: calls 2", () => {
).not.toBe(left.functionFingerprints[0]?.components.literalSetSha256);
});
it("keeps nested callable syntax out of its owner's fingerprint", () => {
const analyze = (nested: number, owned: number) =>
analyzeJavaScriptSemantics(`
function outer() {
function inner() { return ${nested}; }
const object = { method() { return ${nested}; } };
class Nested { method() { return ${nested}; } }
return ${owned};
}
`);
const first = analyze(1, 2);
const changedNested = analyze(3, 2);
const changedOwner = analyze(1, 4);
const syntax = (ir: typeof first) =>
ir.functionFingerprints.map(({ components }) => ({
ast: components.normalizedAstSha256,
control: components.controlFlowSha256,
literals: components.literalSetSha256,
}));
const original = syntax(first);
expect(original).toHaveLength(4);
expect(syntax(changedNested)[0]).toEqual(original[0]);
for (const index of [1, 2, 3])
expect(syntax(changedNested)[index]).not.toEqual(original[index]);
expect(syntax(changedOwner)[0]).not.toEqual(original[0]);
expect(syntax(changedOwner).slice(1)).toEqual(original.slice(1));
});
it("keeps fingerprint relations ordered and effects scoped to their owner", () => {
const ordered = analyzeJavaScriptSemantics(`
function first() {}
@@ -63,6 +63,35 @@ it("traverses a large tree in steps with the synchronous visit order (#1462)", (
expect(stepped).toEqual(synchronous);
});
it("skips child subtrees without changing sibling ancestry or exit callbacks", () => {
const parsed = parseJavaScriptSource("[1, [2], 3]", "selection.js");
if (parsed === null) throw new Error("Expected parsed source");
const entered: number[] = [];
const exited: number[] = [];
const parents: string[][] = [];
const steps = traverseJavaScriptAstSteps(parsed.program, {
skip: (node) => node.type === "ArrayExpression" && node.start === 4,
enter: (node, parent, readAncestors) => {
if (node.type !== "NumericLiteral") return;
entered.push(node.value);
expect(readAncestors().at(-1)).toBe(parent);
parents.push(readAncestors().map(({ type }) => type));
},
exit: (node) => {
if (node.type === "NumericLiteral") exited.push(node.value);
},
});
while (steps.next().done !== true) {
// Complete the same cooperative traversal used by fingerprint collection.
}
expect(entered).toEqual([1, 3]);
expect(exited).toEqual([1, 3]);
expect(parents).toEqual([
["Program", "ExpressionStatement", "ArrayExpression"],
["Program", "ExpressionStatement", "ArrayExpression"],
]);
});
it("preserves receiver and Electron alias scope across traversal pauses (#1462)", () => {
const padding = Array.from(
{ length: 400 },
@@ -73,7 +73,7 @@ export function* collectJavaScriptSemanticFingerprintsSteps(
const node = state.callableNodesById.get(callable.callableId);
if (node === undefined) continue;
yield;
const syntax = yield* fingerprintSyntaxSteps(node, callable.callableId);
const syntax = yield* fingerprintSyntaxSteps(node);
const promiseEffects = promiseEffectsByOwner.get(callable.callableId) ?? [];
const eventEffects = eventEffectsByOwner.get(callable.callableId) ?? [];
const timerEffects = timerEffectsByOwner.get(callable.callableId) ?? [];
@@ -164,28 +164,19 @@ interface FingerprintSyntax {
function* fingerprintSyntaxSteps(
root: t.Node,
targetCallableId: string,
): Generator<void, FingerprintSyntax> {
const normalizedTokens: string[] = [];
const controlFlowTokens: string[] = [];
const literals: string[] = [];
const callableStack: string[] = [];
yield* traverseJavaScriptAstSteps(root, {
skip: (node) => semanticCallableIdForNode(node) !== null,
enter: (node, parent) => {
const callableId = semanticCallableIdForNode(node);
if (callableId !== null) callableStack.push(callableId);
if (callableStack.at(-1) !== targetCallableId) return;
normalizedTokens.push(normalizedNodeToken(node, parent));
const control = controlFlowToken(node);
if (control !== null) controlFlowTokens.push(control);
const literal = semanticLiteral(node);
if (literal !== null) literals.push(literal);
},
exit: (node) => {
const callableId = semanticCallableIdForNode(node);
if (callableId !== null && callableStack.at(-1) === callableId)
callableStack.pop();
},
});
return { normalizedTokens, controlFlowTokens, literals };
}
@@ -1,7 +1,7 @@
import * as t from "@babel/types";
/**
* Visit every Babel AST node in deterministic source-tree order.
* Visit Babel AST nodes in deterministic source-tree order, excluding skipped subtrees.
*
* `readAncestors` returns a snapshot during `enter`, outermost-first and
* ending with the direct parent. Callers
@@ -17,6 +17,8 @@ export const traverseJavaScriptAst = (
/** Callbacks for one deterministic AST traversal. */
export interface JavaScriptAstVisitor {
/** Omit a child and its subtree without entering or exiting it. */
readonly skip?: (node: t.Node) => boolean;
readonly enter: (
node: t.Node,
parent: t.Node | null,
@@ -50,6 +52,7 @@ export function* traverseJavaScriptAstSteps(
current.nextIndex += 1;
if (visited % 1024 === 0) yield;
visited += 1;
if (visitor.skip?.(child) === true) continue;
pending.push(enter(child, current.node));
} else {
visitor.exit?.(current.node, current.parent);
+12
View File
@@ -38,6 +38,18 @@ describe("managed projection admission", () => {
});
describe("managed decoding bounds", () => {
it("bounds new row identities without charging lookup replay or merging tables", () => {
const budget = new ManagedDecodeBudget();
budget.reserve(64 * 1024 * 1024 - 512, null);
budget.reserveRow(2, 1, 100);
budget.reserveRow(12, 1, 200);
expect(() => budget.reserveRow(2, 1, 100)).not.toThrow();
expect(() => budget.reserveRow(2, 2, 300)).toThrow(ManagedReaderFailure);
// A rejected row has no retained reservation; replay cannot bypass capacity.
expect(() => budget.reserveRow(2, 2, 300)).toThrow(ManagedReaderFailure);
});
it("keeps concurrent decoding bounds within one budget until released", () => {
const budget = new ManagedDecodeBudget();
const bound = 40 * 1024 * 1024;
+13
View File
@@ -15,6 +15,7 @@ interface CachedString {
export class ManagedDecodeBudget {
#remaining = MAX_METADATA_REPRESENTATION_BYTES;
#transient = 0;
readonly #rows = new Map<number, Set<number>>();
readonly #strings = new Map<number, CachedString>();
readonly #digests = new WeakMap<ArrayBufferLike, Map<string, string>>();
@@ -23,6 +24,18 @@ export class ManagedDecodeBudget {
this.#remaining -= bytes;
}
/** Retain one bookkeeping reservation per physical row, independently of lookup replay. */
reserveRow(table: number, row: number, offset: number): void {
let rows = this.#rows.get(table);
if (rows?.has(row) === true) return;
this.reserve(256, offset);
if (rows === undefined) {
rows = new Set<number>();
this.#rows.set(table, rows);
}
rows.add(row);
}
/** Bound a decoding allocation that stays live until `releaseTransient`; only retained output is reserved. */
admitTransient(bytes: number, offset: number | null): void {
this.#admit(bytes, offset);
+3 -2
View File
@@ -245,8 +245,9 @@ export const metadataRowCursor = (
"Metadata table is absent",
start,
);
// Reserve per-row object/index bookkeeping before readers retain decoded facts.
managedDecodeBudget(layout).reserve(256, start);
// Temporary cursors may revisit a row while resolving owners or references.
// Bind fixed retained bookkeeping to that row's identity, not each lookup.
managedDecodeBudget(layout).reserveRow(table, row, start);
return new MetadataRowCursor(
bytes,
start,
+48 -23
View File
@@ -3,6 +3,8 @@ import { createHash } from "node:crypto";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
interface ManagedPeFixtureOptions {
readonly additionalEmptyTypes?: number;
readonly customAttributeRowCount?: number;
readonly cliFlags?: number;
readonly corruptMetadataSignature?: boolean;
readonly customAttributeTypeRaw?: number;
@@ -20,6 +22,7 @@ interface ManagedPeFixtureOptions {
readonly malformedCustomAttributeRows?: readonly number[];
readonly metadataValidMaskExtra?: bigint;
readonly methodName?: string;
readonly methodFlags?: number;
readonly methodSignature?: Buffer;
readonly moduleRowCount?: number;
readonly assemblyRowCount?: number;
@@ -328,22 +331,30 @@ const assemblyRefRow = (
metadataIndex(0, blobSize),
]);
const customAttributeRow = (
value: number,
options: ManagedPeFixtureOptions,
parentIndexSize: 2 | 4,
typeIndexSize: MetadataIndexSize,
blobSize: MetadataIndexSize,
): Buffer =>
const customAttributeRow = ({
value,
options,
parentIndexSize,
typeIndexSize,
blobSize,
row,
}: {
readonly value: number;
readonly options: ManagedPeFixtureOptions;
readonly parentIndexSize: 2 | 4;
readonly typeIndexSize: MetadataIndexSize;
readonly blobSize: MetadataIndexSize;
readonly row: number;
}): Buffer =>
Buffer.concat([
parentIndexSize === 2
? u16(
options.malformedCustomAttributeRows?.includes(1)
options.malformedCustomAttributeRows?.includes(row)
? 0xffff
: (1 << 5) | 14,
)
: u32(
options.malformedCustomAttributeRows?.includes(1)
options.malformedCustomAttributeRows?.includes(row)
? 0xffff_ffff
: (1 << 5) | 14,
),
@@ -484,6 +495,7 @@ interface FixtureMetadataRowContext {
readonly attributeNamespace: number;
readonly constructorName: number;
readonly typeName: number;
readonly additionalTypeNames: readonly number[];
readonly typeNamespace: number;
readonly fieldName: number;
readonly methodName: number;
@@ -536,15 +548,16 @@ const customAttributeRows = (
): readonly Buffer[] =>
options.targetFramework === null
? []
: [
customAttributeRow(
indexes.attributeBlob,
: Array.from({ length: options.customAttributeRowCount ?? 1 }, (_, index) =>
customAttributeRow({
value: indexes.attributeBlob,
options,
widths.hasCustomAttribute,
widths.customAttributeType,
heapSizes.blobs,
),
];
parentIndexSize: widths.hasCustomAttribute,
typeIndexSize: widths.customAttributeType,
blobSize: heapSizes.blobs,
row: index + 1,
}),
);
const exportedTypeTable = (
options: ManagedPeFixtureOptions,
@@ -577,12 +590,17 @@ const fixtureIndexWidths = ({
const rowCounts = new Map<number, number>([
[0, options.moduleRowCount ?? 1],
[1, 1],
[2, 1],
[2, indexes.additionalTypeNames.length + 1],
[4, 1],
[6, 1],
[8, 0],
[10, 1],
[12, options.targetFramework === null ? 0 : 1],
[
12,
options.targetFramework === null
? 0
: (options.customAttributeRowCount ?? 1),
],
...(indexes.pinvokeModuleName === null ? [] : ([[26, 1]] as const)),
...(indexes.pinvokeImportName === null ? [] : ([[28, 1]] as const)),
[32, options.assemblyRowCount ?? 1],
@@ -648,9 +666,9 @@ const fixtureMetadataRows = ({
],
[
2,
[
[...indexes.additionalTypeNames, indexes.typeName].map((name) =>
typeDefRow({
name: indexes.typeName,
name,
namespace: indexes.typeNamespace,
fieldList: 1,
methodList: 1,
@@ -662,7 +680,7 @@ const fixtureMetadataRows = ({
? {}
: { extendsRaw: options.extendsRaw }),
}),
],
),
],
[
4,
@@ -685,7 +703,9 @@ const fixtureMetadataRows = ({
blobSize: heapSizes.blobs,
parameterSize: widths.table(8),
rva: methodRva,
flags: options.pinvoke === undefined ? 0x0016 : 0x2016,
flags:
options.methodFlags ??
(options.pinvoke === undefined ? 0x0016 : 0x2016),
}),
],
],
@@ -774,6 +794,10 @@ const buildManagedFixtureMetadata = (
const attributeNamespace = strings.add("System.Runtime.Versioning");
const constructorName = strings.add(".ctor");
const typeName = strings.add(options.typeName ?? "Program");
const additionalTypeNames = Array.from(
{ length: options.additionalEmptyTypes ?? 0 },
(_, index) => strings.add(`Empty${String(index)}`),
);
const typeNamespace = strings.add(options.typeNamespace ?? "Fixture");
const fieldName = strings.add(options.fieldName ?? "counter");
const methodName = strings.add(options.methodName ?? "Main");
@@ -825,6 +849,7 @@ const buildManagedFixtureMetadata = (
attributeNamespace,
constructorName,
typeName,
additionalTypeNames,
typeNamespace,
fieldName,
methodName,
+4 -1
View File
@@ -19,6 +19,7 @@ import {
import type { FirmwareRequest } from "../domain/firmware/firmwareAnalysis.js";
import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";
import { FIRMWARE_LIMITS } from "./FirmwareRelease.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
/** One regular file or unpublished filesystem entry in a private extraction. */
export interface FirmwareEntry {
@@ -261,7 +262,9 @@ export const inventoryFirmwareOutput = async (
});
}
}
return entries.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
return entries.sort((a, b) =>
compareUnicodeCodePoints(a.relativePath, b.relativePath),
);
};
/** Bind producer paths to the selected input or private extraction tree. */
+47 -1
View File
@@ -77,6 +77,47 @@ describe("firmware producer boundaries", () => {
});
describe("Unblob multi-file extraction diagnostics", () => {
it("names a missing extractor dependency and stage while retaining the raw report", () => {
const dependencyFailure = {
__typename__: "ExtractorDependencyNotFoundReport",
severity: "ERROR",
dependencies: ["sasquatch"],
};
const record = root();
const normalized = normalizeUnblobReport(
[
{
...record,
reports: [
...record.reports.filter(
(item) => item.__typename__ !== "UnknownChunkReport",
),
{
__typename__: "ChunkReport",
id: "gzip-id",
start_offset: 0,
end_offset: 20,
size: 20,
handler_name: "gzip",
is_encrypted: false,
extraction_reports: [dependencyFailure],
},
],
},
],
context,
);
expect(normalized.coverage).toBe("partial");
expect(normalized.diagnostics).toEqual([
{
input_path: "$input",
stage: "gzip",
missing_dependencies: ["sasquatch"],
report: dependencyFailure,
},
]);
});
it("retains nested MultiFile extraction failures in partial coverage", () => {
const outputPath = `${context.outputRoot}/multi`;
const childTask = {
@@ -130,7 +171,12 @@ describe("Unblob multi-file extraction diagnostics", () => {
expect(normalized.coverage).toBe("partial");
expect(normalized.diagnostics).toEqual([
{ input_path: "$output/multi", report: multiFileReport },
{
input_path: "$output/multi",
stage: "multipart-firmware",
missing_dependencies: ["sasquatch"],
report: multiFileReport,
},
]);
});
});
+61 -2
View File
@@ -68,6 +68,53 @@ const known = new Set([
"MultiFileReport",
]);
const dependencyFailure = z.object({
__typename__: z.literal("ExtractorDependencyNotFoundReport"),
dependencies: z.array(z.string().min(1)).min(1),
});
/** Collect the named extractors from any dependency report nested in one value. */
const missingDependencies = (value: unknown): string[] => {
const found: string[] = [];
const visit = (node: unknown): void => {
if (Array.isArray(node)) {
for (const item of node) visit(item);
return;
}
if (typeof node !== "object" || node === null) return;
const failure = dependencyFailure.safeParse(node);
if (failure.success) {
for (const dependency of failure.data.dependencies)
if (!found.includes(dependency)) found.push(dependency);
return;
}
for (const child of Object.values(node)) visit(child);
};
visit(value);
return found;
};
/**
* Name the missing extractors and the producing stage for one extraction
* problem so a caller can act without decoding the raw report. The original
* report stays retained alongside the normalized fields.
*/
const extractionDiagnostic = (
inputPath: string,
stage: string | null,
report: JsonValue,
): JsonValue => {
const dependencies = missingDependencies(report);
return {
input_path: inputPath,
...(stage === null ? {} : { stage }),
...(dependencies.length === 0
? {}
: { missing_dependencies: dependencies }),
report,
};
};
/** Interpret the pinned Binwalk report without inventing validated region lengths. */
export const normalizeBinwalkReport = (
raw: unknown,
@@ -234,7 +281,13 @@ export const normalizeUnblobReport = (
: null;
if (detail !== null)
for (const problem of detail.extraction_reports)
diagnostics.push({ input_path: path, report: problem });
diagnostics.push(
extractionDiagnostic(
path,
detail.handler_name,
jsonValueSchema.parse(problem),
),
);
chunks.push({
input_path: path,
provider_id: parsed.id,
@@ -253,7 +306,13 @@ export const normalizeUnblobReport = (
if (item.__typename__ === "MultiFileReport") {
const parsed = multiFile.parse(item);
if (parsed.extraction_reports.length > 0)
diagnostics.push({ input_path: path, report: item });
diagnostics.push(
extractionDiagnostic(
path,
parsed.handler_name,
jsonValueSchema.parse(item),
),
);
}
}
}
+2 -1
View File
@@ -6,6 +6,7 @@ import { readWindowsPrivateRuntimeFile } from "../windows/WindowsPrivateRuntime.
import { err, ok, type Result } from "../domain/result.js";
import { GhidraSessionError } from "./GhidraSessionError.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
/** Local bridge transports used by the current Ghidra session. */
export type GhidraTransportKind = "unix-socket" | "authenticated-loopback-tcp";
@@ -147,7 +148,7 @@ const hasExactKeys = (
expected: readonly string[],
): value is Record<string, unknown> => {
const keys = Object.keys(value).sort((left, right) =>
left.localeCompare(right),
compareUnicodeCodePoints(left, right),
);
return (
keys.length === expected.length &&
+6 -4
View File
@@ -355,7 +355,10 @@ export const inspectSourceMapValue = (
}
const leaf = inspectLeaf(node, budget, options);
leaves.push({ map: leaf, offset: node.offset, stop: node.stop });
if (options.profile !== "browser-collection")
if (options.profile !== "browser-collection") {
const ignoredSources = new Set(
leaf.ignoreList ?? leaf.x_google_ignoreList ?? [],
);
for (const [sourceIndex, source] of leaf.sources.entries())
declarations.push({
sectionPath: node.path,
@@ -363,10 +366,9 @@ export const inspectSourceMapValue = (
source,
root: leaf.sourceRoot ?? null,
content: leaf.sourcesContent?.[sourceIndex] ?? null,
ignored: (leaf.ignoreList ?? leaf.x_google_ignoreList ?? []).includes(
sourceIndex,
),
ignored: ignoredSources.has(sourceIndex),
});
}
}
return {
format: root.sections === undefined ? "regular" : "indexed",
@@ -29,6 +29,47 @@ it("traces BOM-prefixed maps with a source-map transport prefix ending in CR", (
});
});
it("keeps ignore-list precedence and section-local indexes for duplicate sources", () => {
const map = {
version: 3,
sections: [
{
offset: { line: 0, column: 0 },
map: {
...leaf,
sources: ["same.ts", "same.ts"],
sourcesContent: ["first", "second"],
mappings: "AAAA,ACAA",
ignoreList: [1, 1],
x_google_ignoreList: [0],
},
},
{
offset: { line: 1, column: 0 },
map: { ...leaf, x_google_ignoreList: [0] },
},
{
offset: { line: 2, column: 0 },
map: { ...leaf, ignoreList: [], x_google_ignoreList: [0] },
},
],
};
expect(trace(map).matches).toMatchObject([
{ source_index: 0, ignored: false, content: { text: "first" } },
{ source_index: 1, ignored: true, content: { text: "second" } },
]);
expect(trace(map, { line: 2, column: 0 }).matches[0]).toMatchObject({
section_path: [1],
source_index: 0,
ignored: true,
});
expect(trace(map, { line: 3, column: 0 }).matches[0]).toMatchObject({
section_path: [2],
source_index: 0,
ignored: false,
});
});
describe("upstream source-map point evidence", () => {
it("preserves every duplicate-column/source-URL candidate and its own embedded bytes", () => {
const report = trace({
+2 -1
View File
@@ -13,6 +13,7 @@ import { parseDyldSymbols } from "./parsers/dyldInfo.js";
import { parseLipoArchitectures } from "./parsers/lipo.js";
import { withoutEchoedPathHeader } from "./parsers/echoedPath.js";
import { parseOtoolLoadCommands } from "./parsers/otool.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
interface NativeMachoObservation {
readonly result: JsonValue;
@@ -270,7 +271,7 @@ const uniqueSymbols = <Value extends { readonly name: string }>(
for (const item of items)
if (!unique.has(item.name)) unique.set(item.name, item);
return [...unique.values()].sort((left, right) =>
left.name.localeCompare(right.name),
compareUnicodeCodePoints(left.name, right.name),
);
};
+20 -4
View File
@@ -7,7 +7,10 @@ import {
ProviderProcessSupervisor,
spawnOwnedProviderProcess,
} from "./ProviderProcess.js";
import { cleanupOwnedProcessGroup } from "./ProcessOwnership.js";
import {
cleanupOwnedProcessGroup,
type ProcessCleanupFailure,
} from "./ProcessOwnership.js";
import {
ProviderStartupDeadline,
waitForAbortableDelay,
@@ -15,16 +18,19 @@ import {
/** A short-lived command failed its lifecycle or complete-output contract. */
export class OwnedCommandFailure extends Error {
readonly cleanupResult: ProcessCleanupFailure | undefined;
constructor(
readonly reason: "cancelled" | "timeout" | "output-limit" | "process",
message: string,
readonly snapshot: ProviderProcessSnapshot | null = null,
readonly cleanupFailure: string | null = null,
options?: ErrorOptions,
options?: ErrorOptions & { readonly cleanupResult?: ProcessCleanupFailure },
readonly resources: readonly string[] = [],
readonly cleanupOwner?: ProviderProcessSupervisor,
) {
super(message, options);
this.cleanupResult = options?.cleanupResult;
}
}
@@ -190,7 +196,12 @@ const collectOwnedCommand = async (
failure?.message ?? "Command cleanup failed.",
snapshot,
stopped.reason,
failure === undefined ? undefined : { cause: failure },
{
...(failure === undefined ? {} : { cause: failure }),
...(stopped.cleanupResult === undefined
? {}
: { cleanupResult: stopped.cleanupResult }),
},
[
spawn.runId,
...(spawn.cwd === undefined ? [] : [spawn.cwd]),
@@ -205,7 +216,12 @@ const collectOwnedCommand = async (
failure.message,
snapshot,
failure.cleanupFailure,
{ cause: failure },
{
cause: failure,
...(failure.cleanupResult === undefined
? {}
: { cleanupResult: failure.cleanupResult }),
},
failure.resources,
);
if (callerSignal?.aborted)
+1 -1
View File
@@ -111,7 +111,7 @@ describe("owned process-group cleanup discovery", () => {
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
{
cleaned: false,
reason: "process tree contains an unowned or PID-reused process",
reason: "process ownership token mismatch for PID(s): 104",
failures: [{ pid: 104, reason: "run-token-mismatch" }],
},
);
+2 -2
View File
@@ -331,7 +331,7 @@ describe("sampled detached process groups during cleanup", () => {
expect(result).toMatchObject({
cleaned: false,
reason: "process tree contains an unowned or PID-reused process",
reason: "process ownership token mismatch for PID(s): 200",
failures: [{ pid: 200, reason: "run-token-mismatch" }],
});
expect(signalGroup).toHaveBeenCalledTimes(1);
@@ -369,7 +369,7 @@ describe("sampled detached process groups during cleanup", () => {
expect(result).toMatchObject({
cleaned: false,
reason: "process tree contains an unowned or PID-reused process",
reason: "process ownership token mismatch for PID(s): 200",
failures: [{ pid: 200, reason: "run-token-mismatch" }],
});
expect(signalGroup).not.toHaveBeenCalled();
+21 -16
View File
@@ -8,6 +8,7 @@ import {
import { launcherIdentityFailure } from "./ProcessOwnershipIdentity.js";
import { descendantsOf, liveProcesses } from "./ProcessOwnershipProcessTree.js";
import { readProcessRunTokens } from "./ProcessRunTokenObservations.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
const execFileAsync = promisify(execFile);
@@ -157,19 +158,15 @@ export type ProcessCleanupResult =
readonly signaled: boolean;
readonly unverified?: readonly OwnershipSweepUnverifiedProcess[];
}
| {
readonly cleaned: false;
readonly reason: string;
readonly failures?: readonly {
readonly pid: number;
readonly reason:
| "environment-unreadable"
| "run-token-mismatch"
| "process-identity-unavailable";
readonly diagnostic?: string;
}[];
readonly unverified?: readonly OwnershipSweepUnverifiedProcess[];
};
| ProcessCleanupFailure;
/** Retained verification failures for one cleanup attempt, without additional signaling authority. */
export interface ProcessCleanupFailure {
readonly cleaned: false;
readonly reason: string;
readonly failures?: readonly ProcessOwnershipValidationFailure[];
readonly unverified?: readonly OwnershipSweepUnverifiedProcess[];
}
/** Token-verified liveness result used by post-root-exit settlement. */
export type ProcessGroupObservation =
@@ -591,7 +588,15 @@ const cleanupValidationFailure = (
if (failures.some(({ reason }) => reason === "run-token-mismatch"))
return {
cleaned: false,
reason: "process tree contains an unowned or PID-reused process",
reason: `process ownership token mismatch for PID(s): ${[
...new Set(
failures
.filter(({ reason }) => reason === "run-token-mismatch")
.map(({ pid }) => pid),
),
]
.sort((left, right) => left - right)
.join(", ")}`,
failures,
...unverifiedEntry,
};
@@ -609,7 +614,7 @@ const cleanupValidationFailure = (
counts.set(category, (counts.get(category) ?? 0) + 1);
}
const breakdown = [...counts]
.sort(([left], [right]) => left.localeCompare(right))
.sort(([left], [right]) => compareUnicodeCodePoints(left, right))
.map(([category, count]) => `${category}=${String(count)}`)
.join(", ");
const candidates = unreadable
@@ -617,7 +622,7 @@ const cleanupValidationFailure = (
({ pid, diagnostic }) =>
`${String(pid)}=${sanitizedTokenReadFailure(diagnostic)}`,
)
.sort((left, right) => left.localeCompare(right));
.sort((left, right) => compareUnicodeCodePoints(left, right));
return {
cleaned: false,
reason: `process ownership token could not be read for ${String(unreadable.length)} live process(es): ${breakdown}; live candidates ${candidates.join(", ")}`,
@@ -74,7 +74,7 @@ describe("owned process-group cleanup validation: ownership and lineage", () =>
});
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
cleaned: false,
reason: "process tree contains an unowned or PID-reused process",
reason: "process ownership token mismatch for PID(s): 101",
failures: [{ pid: 101, reason: "run-token-mismatch" }],
});
expect(signalGroup).not.toHaveBeenCalled();
@@ -106,7 +106,7 @@ describe("owned process-group cleanup validation: ownership and lineage", () =>
};
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
cleaned: false,
reason: "process tree contains an unowned or PID-reused process",
reason: "process ownership token mismatch for PID(s): 101",
failures: [
expect.objectContaining({
pid: 100,
@@ -189,7 +189,7 @@ describe("owned process-group cleanup liveness rechecks", () => {
cleanupOwnedProcessGroup(ownership, adapter),
).resolves.toEqual({
cleaned: false,
reason: "process tree contains an unowned or PID-reused process",
reason: "process ownership token mismatch for PID(s): 101",
failures: recheckFails
? [
{
@@ -345,7 +345,7 @@ describe("owned process-group cleanup validation: launcher exit races", () => {
if (remaining === "foreign")
expect(result).toMatchObject({
cleaned: false,
reason: "process tree contains an unowned or PID-reused process",
reason: "process ownership token mismatch for PID(s): 101",
});
else
expect(result).toEqual({
+16 -3
View File
@@ -6,6 +6,7 @@ import { WindowsOwnedProcess } from "../windows/WindowsOwnedProcess.js";
import type {
OwnedProcessGroup,
ProcessCleanupFailure,
ProcessCleanupResult,
} from "./ProcessOwnership.js";
import { prepareProcessOwnershipInspection } from "./ProcessOwnershipObservation.js";
@@ -143,7 +144,11 @@ export type ProviderProcessStopResult =
| "terminated"
| "killed";
}
| { readonly status: "incomplete"; readonly reason: string };
| {
readonly status: "incomplete";
readonly reason: string;
readonly cleanupResult?: ProcessCleanupFailure;
};
/**
* Spawn a provider in an owned Windows job or dedicated POSIX process group.
@@ -373,13 +378,21 @@ export class ProviderProcessSupervisor {
if (this.launch.cleanup !== undefined) {
const cleanup = await this.#ownedCleanup(options.cleanupResult);
if (!cleanup.cleaned)
return { status: "incomplete", reason: cleanup.reason };
return {
status: "incomplete",
reason: cleanup.reason,
cleanupResult: cleanup,
};
const graceMs = options.killGraceMs ?? DEFAULT_KILL_GRACE_MS;
if (await this.waitForExit(graceMs))
return { status: "verified-cleanup" };
const retried = await this.launch.cleanup();
if (!retried.cleaned)
return { status: "incomplete", reason: retried.reason };
return {
status: "incomplete",
reason: retried.reason,
cleanupResult: retried,
};
if (await this.waitForExit(graceMs))
return { status: "verified-cleanup" };
return {
+23 -2
View File
@@ -1,9 +1,13 @@
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import { AndroidAnalysisService } from "../application/android/AndroidAnalysisService.js";
import { summarizeRetainedAndroidSearch } from "../application/android/AndroidSearchEvidenceSummary.js";
import { toolContract } from "../contracts/toolContracts.js";
import type { Logger } from "pino";
import { createContractToolHandler } from "./contractToolHandler.js";
import {
createContractToolHandler,
type ContractToolService,
} from "./contractToolHandler.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
@@ -22,6 +26,23 @@ export const registerAndroidTools = (
recordEvidence,
withAdmittedAnalysis,
);
// Focused class searches keep complete raw inventory in the retained
// record and deliver a bounded summary inline; the generic handler then
// records and delivers the summary as the search contract's Evidence.
const searchService: ContractToolService<"search_android_classes"> = {
execute: async (operation, input, options) => {
const executed = await service.execute(operation, input, options);
if (!executed.ok) return executed;
return summarizeRetainedAndroidSearch(executed.value, recordEvidence);
},
};
const searchHandler = createContractToolHandler(
server,
searchService,
logger,
recordEvidence,
withAdmittedAnalysis,
);
const packageContract = toolContract("inspect_android_package");
server.registerTool(
packageContract.name,
@@ -32,7 +53,7 @@ export const registerAndroidTools = (
server.registerTool(
searchContract.name,
toolRegistrationOptions(searchContract),
handler(searchContract),
searchHandler(searchContract),
);
const classContract = toolContract("inspect_android_class");
server.registerTool(
@@ -5,6 +5,7 @@ import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import { err, ok, type Result } from "../../domain/result.js";
import { recordDerivedEvidence } from "../recordDerivedEvidence.js";
import type { WorkflowUnknownInput } from "./types.js";
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
export const isIncomplete = (status: string): boolean =>
status === "unknown" || status === "truncated";
@@ -21,7 +22,9 @@ export const functionEvidenceIds = (records: readonly Evidence[]): string[] =>
uniqueIds(records.map(({ evidence_id }) => evidence_id));
const uniqueIds = (ids: readonly string[]): string[] =>
[...new Set(ids)].sort((left, right) => left.localeCompare(right));
[...new Set(ids)].sort((left, right) =>
compareUnicodeCodePoints(left, right),
);
export const evidenceClosure = (
session: BinarySessionPort,
@@ -37,6 +37,18 @@ const INTRINSIC_MUTATIONS = [
'const change = Object.defineProperty.bind(null,Object,"create"); change({value:customCreate});',
],
["receiver.cjs", 'Reflect.set({},"create",customCreate,Object);'],
[
"sequence.cjs",
'(0,Object.defineProperty)(Object,"create",{value:customCreate});',
],
[
"deep-call.cjs",
'Function.prototype.call.call.call(Object.defineProperty,null,Object,"create",{value:customCreate});',
],
[
"deep-apply.cjs",
'Function.prototype.apply.apply(Object.defineProperty,[null,[Object,"create",{value:customCreate}]]);',
],
] as const;
const writePoisonedModules = async (root: string): Promise<void> => {
@@ -81,6 +93,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
function hoistedFunction() {}
const captured = Object.defineProperty;
Object.defineProperty = custom;
captured.call(null,metadata,"captured",{value:1});
${ROLLDOWN_MODULE_INTEROP.replace("__defProp = Object.defineProperty", "__defProp = captured")}
let electron = require("electron");
electron = __toESM(electron, 1);
@@ -111,6 +124,9 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
require("./generic-bind.cjs");
require("./replaced-apply.cjs");
require("./receiver.cjs");
require("./sequence.cjs");
require("./deep-call.cjs");
require("./deep-apply.cjs");
throw new Error("must not execute main");
`;
await writeFile(join(root, "main.cjs"), source);
@@ -137,7 +153,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
preload_entrypoints: 1,
});
expect(result.statistics.parse_failures).toBe(0);
expect(result.statistics.parsed_javascript_files).toBe(10);
expect(result.statistics.parsed_javascript_files).toBe(13);
const windows = result.graph.nodes.filter(
({ kind }) => kind === "browser-window",
);
@@ -0,0 +1,251 @@
import { createHash } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { dirname, join, relative } from "node:path";
import { expect } from "vitest";
import { z } from "zod";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
const literalAliases = ["#/x", "#x%2Fy", "#x%2Ey", "#x\\y", "#x\0y"];
const fallbackAliases = {
"#inactive-array": {
node: [{ browser: "./browser.cjs" }],
default: "./config.cjs",
},
"#nested-inactive-array": {
node: [[{ browser: "./browser.cjs" }]],
default: "./config.cjs",
},
"#parent": ["../outside.cjs", "./config.cjs"],
"#absolute": { node: [["/outside.cjs"], "./config.cjs"] },
"#url": {
import: ["https://example.invalid/outside.cjs", "./config.cjs"],
require: ["file:///outside.cjs", "./config.cjs"],
},
};
const resolvedAliases = [...literalAliases, ...Object.keys(fallbackAliases)];
const refusedAliases = {
"#empty": { target: [], limitation: "an empty imports target array" },
"#empty-active": {
target: { node: [] },
limitation: "an empty imports target array",
},
"#null-last": {
target: [[], null],
limitation: "an explicit null imports target",
},
"#empty-last": {
target: [null, []],
limitation: "an empty imports target array",
},
"#inactive": {
target: [{ browser: "./browser.cjs" }],
limitation: "it declares browser.",
},
"#nested-inactive": {
target: [
[{ browser: "./browser.cjs" }, { "rea-inactive": "./inactive.cjs" }],
],
limitation: "it declares browser, rea-inactive.",
},
};
const allAliases = [...resolvedAliases, ...Object.keys(refusedAliases)];
const createPackageImportAliasFixture = async () => {
const root = await createTestTempDirectory("rea-package-import-aliases-");
const mainSource = [
'const config = require("#config");',
'const nested = require("./node_modules/fixture/index.cjs");',
'const missing = require("#missing");',
...allAliases.map((specifier) => `require(${JSON.stringify(specifier)});`),
].join("\n");
const moduleSource = allAliases
.map((specifier) => `import ${JSON.stringify(specifier)};`)
.join("\n");
const nestedSource = [
'const config = require("#config");',
"module.exports = config;",
].join("\n");
const files = {
"package.json": JSON.stringify({
name: "app",
imports: {
"#config": "./config.cjs",
...Object.fromEntries(
literalAliases.map((specifier) => [specifier, "./config.cjs"]),
),
...fallbackAliases,
...Object.fromEntries(
Object.entries(refusedAliases).map(([specifier, { target }]) => [
specifier,
target,
]),
),
},
}),
"main.cjs": mainSource,
"main.mjs": moduleSource,
"config.cjs": "module.exports = 'app-config';",
"node_modules/fixture/package.json": JSON.stringify({
name: "fixture",
imports: { "#config": "./local.cjs" },
}),
"node_modules/fixture/index.cjs": nestedSource,
"node_modules/fixture/local.cjs": "module.exports = 'fixture-config';",
};
await Promise.all(
Object.entries(files).map(async ([path, content]) => {
const absolute = join(root, path);
await mkdir(dirname(absolute), { recursive: true });
await writeFile(absolute, content);
}),
);
return { root, mainSource, moduleSource, nestedSource };
};
cliTest.for(["CLI", "stdio MCP"] as const)(
"resolves exact package import aliases with package scope through %s",
async (surface, { cli }) => {
const { root, mainSource, moduleSource, nestedSource } =
await createPackageImportAliasFixture();
const nativeRequire = createRequire(join(root, "main.cjs"));
expect(
relative(root, nativeRequire.resolve("#config")).replaceAll("\\", "/"),
).toBe("config.cjs");
expect(
relative(
root,
createRequire(join(root, "node_modules/fixture/index.cjs")).resolve(
"#config",
),
).replaceAll("\\", "/"),
).toBe("node_modules/fixture/local.cjs");
expect(() => nativeRequire.resolve("#missing")).toThrow(
expect.objectContaining({ code: "ERR_PACKAGE_IMPORT_NOT_DEFINED" }),
);
let document: unknown;
if (surface === "CLI") {
const response = await cli.run({
arguments: ["analyze-javascript-application", root, "--format", "json"],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(response.exitCode, response.stderr).toBe(0);
document = response.json;
} else {
const { call } = await connectLocalToolsMcp();
const response = await call("analyze_javascript_application", {
input_path: root,
format: "directory",
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
document = response.structuredContent;
}
const { graph } = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(document).normalized_result;
for (const specifier of resolvedAliases)
for (const [moduleKind, sourcePath, source] of [
["require", "main.cjs", mainSource],
["import", "main.mjs", moduleSource],
] as const)
expect(graph.edges).toContainEqual(
expect.objectContaining({
properties: expect.objectContaining({
module_link_kind: moduleKind,
specifier,
resolved_path: "config.cjs",
resolution_status: "resolved",
}),
evidence: sourceEvidence(sourcePath, source),
}),
);
const imports = graph.edges.filter(
({ properties }) => properties.module_link_kind === "require",
);
for (const [specifier, { limitation }] of Object.entries(refusedAliases))
for (const [moduleKind, sourcePath, source] of [
["require", "main.cjs", mainSource],
["import", "main.mjs", moduleSource],
] as const)
expect(graph.edges).toContainEqual(
expect.objectContaining({
properties: expect.objectContaining({
module_link_kind: moduleKind,
specifier,
resolved_path: null,
resolution_status: "external",
}),
evidence: sourceEvidence(sourcePath, source, limitation),
}),
);
expect(imports).toContainEqual(
expect.objectContaining({
properties: expect.objectContaining({
specifier: "#config",
resolved_path: "config.cjs",
resolution_status: "resolved",
}),
evidence: sourceEvidence("main.cjs", mainSource),
}),
);
expect(imports).toContainEqual(
expect.objectContaining({
properties: expect.objectContaining({
specifier: "#config",
resolved_path: "node_modules/fixture/local.cjs",
resolution_status: "resolved",
}),
evidence: sourceEvidence(
"node_modules/fixture/index.cjs",
nestedSource,
),
}),
);
expect(imports).toContainEqual(
expect.objectContaining({
properties: expect.objectContaining({
specifier: "#missing",
resolved_path: null,
resolution_status: "external",
}),
evidence: expect.objectContaining({
limitations: expect.arrayContaining([
expect.stringContaining("does not define package import alias"),
]),
}),
}),
);
},
);
const sourceEvidence = (
sourcePath: string,
source: string,
limitation?: string,
): unknown =>
expect.objectContaining({
artifact: expect.objectContaining({
available: true,
sha256: createHash("sha256").update(source).digest("hex"),
}),
location: expect.objectContaining({
available: true,
value: expect.objectContaining({
kind: "source-range",
source: sourcePath,
}),
}),
...(limitation === undefined
? {}
: {
limitations: expect.arrayContaining([
expect.stringContaining(limitation),
]),
}),
});
+66
View File
@@ -7,6 +7,72 @@ import { buildManagedPeFixture } from "../../src/dotnet/ManagedPe.fixture.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
import { cliTest } from "../support/cli/cliFixture.js";
cliTest(
"managed CLI retains metadata and CIL after repeated local constructor owner lookups",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-managed-row-lookup-");
const path = join(root, "local-attributes.dll");
await writeFile(
path,
buildManagedPeFixture({
additionalEmptyTypes: 512,
customAttributeRowCount: 512,
customAttributeTypeRaw: (1 << 3) | 2,
typeName: "LookupAttribute",
extendsRaw: 0,
methodName: ".ctor",
methodFlags: 0x1886,
methodSignature: Buffer.from([0x20, 0x01, 0x01, 0x0e]),
ilBody: Buffer.from([0x06, 0x2a]),
}),
);
const artifact = await cli.run({
arguments: ["inspect-managed-artifact", path, "--json"],
});
expect(artifact.exitCode).toBe(0);
expect(artifact.json).toMatchObject({
normalized_result: {
coverage: { state: "complete", issues: [] },
attributes: expect.arrayContaining([
expect.objectContaining({
type_name: "Fixture.LookupAttribute",
constructor_token: "0x06000001",
}),
]),
},
});
expect(artifact.json).toHaveProperty(
"normalized_result.attributes.length",
512,
);
const members = await cli.run({
arguments: ["inspect-managed-members", path, "--json"],
});
expect(members.exitCode).toBe(0);
expect(members.json).toMatchObject({
normalized_result: {
coverage: { state: "complete", issues: [] },
types: expect.arrayContaining([
expect.objectContaining({ full_name: "Fixture.Empty0" }),
expect.objectContaining({ full_name: "Fixture.Empty511" }),
expect.objectContaining({ full_name: "Fixture.LookupAttribute" }),
]),
methods: [
expect.objectContaining({
name: ".ctor",
declaring_type: "Fixture.LookupAttribute",
body: expect.objectContaining({
status: "present",
instruction_count: 1,
}),
}),
],
},
});
expect(members.json).toHaveProperty("normalized_result.types.length", 513);
},
);
cliTest(
"managed CLI separates .NET Standard API targets from runtime evidence",
async ({ cli }) => {
@@ -29,6 +29,11 @@ const chromeExecutable = [
existsSync(candidate),
);
// Match the real-browser verifier: a cold Chrome launch on a loaded coverage
// runner can exceed 20 seconds before publishing DevToolsActivePort.
const CHROME_STARTUP_TIMEOUT_MS = 60_000;
const CHROME_TEST_TIMEOUT_MS = CHROME_STARTUP_TIMEOUT_MS + 30_000;
// Issue 1586's page, plus the HTML, image, use, and foreign-origin cases the
// real snapshot must distinguish. The XHTML page is the prefixed-svg gap
// reported on PR 1602. The tests are skipped when no Chrome-family executable
@@ -90,7 +95,7 @@ it.skipIf(chromeExecutable === undefined)(
executable,
activePortPath: join(profile, "DevToolsActivePort"),
stderr: () => stderr,
timeoutMs: 20_000,
timeoutMs: CHROME_STARTUP_TIMEOUT_MS,
});
const endpoint = `http://127.0.0.1:${String(port)}`;
const provider = new CdpBrowserProvider();
@@ -158,6 +163,7 @@ it.skipIf(chromeExecutable === undefined)(
});
}
},
CHROME_TEST_TIMEOUT_MS,
);
const xhtmlPage = `<?xml version="1.0" encoding="UTF-8"?>
@@ -261,7 +267,7 @@ for (const { format, page, contentType, nodeNames, link, destinations } of [
executable,
activePortPath: join(profile, "DevToolsActivePort"),
stderr: () => stderr,
timeoutMs: 20_000,
timeoutMs: CHROME_STARTUP_TIMEOUT_MS,
});
const endpoint = `http://127.0.0.1:${String(port)}`;
const provider = new CdpBrowserProvider();
@@ -312,6 +318,7 @@ for (const { format, page, contentType, nodeNames, link, destinations } of [
});
}
},
CHROME_TEST_TIMEOUT_MS,
);
}
@@ -308,6 +308,8 @@ it.each(["depth", "dependency", "link"])(
expect(normalized.diagnostics).toEqual([
{
input_path: "$input",
stage: "gzip",
missing_dependencies: ["sasquatch"],
report: {
__typename__: "ExtractorDependencyNotFoundReport",
severity: "ERROR",
@@ -1,8 +1,11 @@
import { writeFile } from "node:fs/promises";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { readFirmwareReport } from "../../../src/firmware/FirmwareFiles.js";
import {
inventoryFirmwareOutput,
readFirmwareReport,
} from "../../../src/firmware/FirmwareFiles.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it.each([
@@ -41,3 +44,24 @@ it("preserves valid Unicode and a literal replacement character in producer JSON
report,
);
});
it("orders extracted firmware paths by code point independently of host locale", async () => {
const root = await createTestTempDirectory("rea-firmware-inventory-");
await mkdir(join(root, "Lib"));
for (const path of ["a.bin", "z.bin", "\u00e4.bin", "B.bin", "Lib/x.bin"])
await writeFile(join(root, path), "");
const entries = await inventoryFirmwareOutput(
root,
1024,
16,
"inspect_firmware_regions",
);
// Locale collation would interleave case and place "ä" by language rules.
expect(entries.map(({ relativePath }) => relativePath)).toEqual([
"B.bin",
"Lib/x.bin",
"a.bin",
"z.bin",
"\u00e4.bin",
]);
});
@@ -742,6 +742,30 @@ describe("nested and array package export targets", () => {
);
});
describe("unmatched package export conditions", () => {
it.each([
[[{ browser: "./default.cjs" }], "browser"],
[
[[{ browser: "./default.cjs" }, { "rea-inactive": "./node.cjs" }]],
"browser, rea-inactive",
],
[{ node: [{ browser: "./default.cjs" }] }, "node, browser"],
] as const)(
"preserves condition names in unmatched target %j",
async (target, declared) => {
for (const moduleKind of ["import", "require"] as const) {
const { node_error, outcome } = await compareWithNode(
target,
moduleKind,
);
expect(node_error).toBe("ERR_PACKAGE_PATH_NOT_EXPORTED");
expect(outcome).toMatchObject({
resolution_status: "external",
resolved_path: null,
});
expect(outcome.limitations[0]).toContain(`It declares ${declared}.`);
}
},
);
it.each(["import", "require"] as const)(
"names the declared conditions for %s",
async (moduleKind) => {
@@ -769,6 +793,31 @@ describe("unmatched package export conditions", () => {
});
});
describe("blocked package export provenance", () => {
it.each([
[[], "an empty exports target array"],
[{ node: [] }, "an empty exports target array"],
[[null, []], "an empty exports target array"],
[[[], null], "an explicit null exports target"],
] as const)(
"preserves the blocking source value in %j",
async (target, limitation) => {
for (const moduleKind of ["import", "require"] as const) {
const { node_error, outcome } = await compareWithNode(
target,
moduleKind,
);
expect(node_error).toBe("ERR_PACKAGE_PATH_NOT_EXPORTED");
expect(outcome).toMatchObject({
resolution_status: "external",
resolved_path: null,
});
expect(outcome.limitations[0]).toContain(limitation);
}
},
);
});
describe("package exports fallback refusal reasons", () => {
it.each([
[{ import: [42, 7] }, "ERR_INVALID_PACKAGE_TARGET", "rejected"],
@@ -0,0 +1,654 @@
import { execFile } from "node:child_process";
import { mkdir, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { dirname, join, relative } from "node:path";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import {
resolveArtifactPathByContext,
type ArtifactPathResolution,
} from "../../../src/application/javascript/JavaScriptArtifactPathResolution.js";
import type { JavaScriptArtifactFile } from "../../../src/domain/javascript/javascriptArtifactFiles.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const execute = promisify(execFile);
const nodeOutcomeSchema = z.strictObject({
target: z.string().nullable(),
error_code: z.string().nullable(),
});
const posixRelative = (root: string, absolute: string): string =>
relative(root, absolute).replaceAll("\\", "/");
const inventory = (
contents: ReadonlyMap<string, string>,
): Map<string, JavaScriptArtifactFile> =>
new Map(
[...contents].map(([path, value]) => [
path,
{
path,
container_sha256: "a".repeat(64),
sha256: "b".repeat(64),
bytes: Buffer.byteLength(value),
inventory_artifact_id: path,
kind: path.endsWith("package.json") ? "package-json" : "javascript",
unpacked: false,
text: { included: true, value },
},
]),
);
const writeTree = async (
root: string,
files: Readonly<Record<string, string>>,
): Promise<Map<string, string>> => {
const contents = new Map<string, string>();
await Promise.all(
Object.entries(files).map(async ([path, value]) => {
const absolute = join(root, path);
await mkdir(dirname(absolute), { recursive: true });
await writeFile(absolute, value);
contents.set(path, value);
}),
);
return contents;
};
const nodeRequireTarget = async (
importer: string,
specifier: string,
): Promise<z.infer<typeof nodeOutcomeSchema>> => {
try {
return {
target: createRequire(importer).resolve(specifier),
error_code: null,
};
} catch (error) {
const code =
error instanceof Error && "code" in error
? z.string().parse(Reflect.get(error, "code"))
: null;
return { target: null, error_code: code };
}
};
const nodeImportTarget = async (
cwd: string,
specifier: string,
): Promise<z.infer<typeof nodeOutcomeSchema>> => {
const { stdout } = await execute(
process.execPath,
[
"--input-type=module",
"-e",
`
try {
const url = await import.meta.resolve(${JSON.stringify(specifier)});
console.log(JSON.stringify({ target: url, error_code: null }));
} catch (error) {
console.log(JSON.stringify({
target: null,
error_code: error.code ?? null,
}));
}
`,
],
{ cwd },
);
return nodeOutcomeSchema.parse(JSON.parse(stdout));
};
const resolveAlias = (
files: Map<string, JavaScriptArtifactFile>,
declaredPath: string,
sourcePath: string,
moduleKind: "import" | "require",
): ArtifactPathResolution =>
resolveArtifactPathByContext({
declaredPath,
sourcePath,
context: "module-specifier",
moduleKind,
files,
});
describe("literal package import keys compared with Node", () => {
it("matches literal imports keys containing path-like bytes in both Node loaders", async () => {
const root = await createTestTempDirectory("rea-import-alias-literal-");
const specifiers = ["#/x", "#x%2Fy", "#x%2Ey", "#x\\y", "#x\0y"];
const contents = await writeTree(root, {
"package.json": JSON.stringify({
imports: Object.fromEntries(
specifiers.map((specifier) => [specifier, "./target.cjs"]),
),
}),
"main.cjs": "module.exports = 1;",
"target.cjs": "module.exports = 1;",
});
const inventoried = inventory(contents);
for (const specifier of specifiers) {
const required = await nodeRequireTarget(
join(root, "main.cjs"),
specifier,
);
expect(required.error_code).toBeNull();
expect(posixRelative(root, required.target ?? "")).toBe("target.cjs");
const imported = await nodeImportTarget(root, specifier);
expect(imported.error_code).toBeNull();
expect(posixRelative(root, fileURLToPath(imported.target ?? ""))).toBe(
"target.cjs",
);
for (const moduleKind of ["require", "import"] as const)
expect(
resolveAlias(inventoried, specifier, "main.cjs", moduleKind),
JSON.stringify({ specifier, moduleKind }),
).toMatchObject({
declared_path: specifier,
resolution_status: "resolved",
resolved_path: "target.cjs",
});
}
});
it("still rejects unsafe selected targets for literal imports keys", async () => {
const root = await createTestTempDirectory("rea-import-alias-target-");
const contents = await writeTree(root, {
"package.json": JSON.stringify({
imports: { "#x%2Fy": "./nested%2Ftarget.cjs" },
}),
"main.cjs": "module.exports = 1;",
"nested/target.cjs": "module.exports = 1;",
});
const inventoried = inventory(contents);
const required = await nodeRequireTarget(join(root, "main.cjs"), "#x%2Fy");
expect(required.error_code).toBe("ERR_INVALID_MODULE_SPECIFIER");
const imported = await nodeImportTarget(root, "#x%2Fy");
expect(imported.error_code).toBe("ERR_INVALID_MODULE_SPECIFIER");
for (const moduleKind of ["require", "import"] as const)
expect(
resolveAlias(inventoried, "#x%2Fy", "main.cjs", moduleKind),
).toMatchObject({ resolution_status: "rejected", resolved_path: null });
});
});
describe("inactive package target arrays compared with Node", () => {
it("continues past inactive arrays in enclosing imports and exports conditions", async () => {
const root = await createTestTempDirectory("rea-inactive-package-array-");
const conditional = {
node: [{ browser: "./browser.cjs" }],
default: "./fallback.cjs",
};
const nested = {
node: [
[{ browser: "./browser.cjs" }],
{ "rea-inactive": "./inactive.cjs" },
],
default: "./fallback.cjs",
};
const contents = await writeTree(root, {
"package.json": JSON.stringify({
imports: { "#conditional": conditional, "#nested": nested },
}),
"main.cjs": "module.exports = 1;",
"fallback.cjs": "module.exports = 1;",
"node_modules/fixture/package.json": JSON.stringify({
name: "fixture",
exports: { ".": conditional, "./nested": nested },
}),
"node_modules/fixture/fallback.cjs": "module.exports = 2;",
});
const inventoried = inventory(contents);
for (const [specifier, expected] of [
["#conditional", "fallback.cjs"],
["#nested", "fallback.cjs"],
["fixture", "node_modules/fixture/fallback.cjs"],
["fixture/nested", "node_modules/fixture/fallback.cjs"],
] as const) {
const required = await nodeRequireTarget(
join(root, "main.cjs"),
specifier,
);
expect(required.error_code, specifier).toBeNull();
expect(posixRelative(root, required.target ?? "")).toBe(expected);
const imported = await nodeImportTarget(root, specifier);
expect(imported.error_code).toBeNull();
expect(posixRelative(root, fileURLToPath(imported.target ?? ""))).toBe(
expected,
);
for (const moduleKind of ["require", "import"] as const)
expect(
resolveAlias(inventoried, specifier, "main.cjs", moduleKind),
).toMatchObject({
declared_path: specifier,
resolution_status: "resolved",
resolved_path: expected,
});
}
});
});
describe("package target refusal evidence compared with Node", () => {
it("keeps empty, null, invalid, and unmatched array outcomes distinct", async () => {
const root = await createTestTempDirectory("rea-inactive-package-refusal-");
const inactive = { browser: "./browser.cjs" };
const contents = await writeTree(root, {
"package.json": JSON.stringify({
imports: {
"#empty-direct": [],
"#empty": { node: [], default: "./fallback.cjs" },
"#null": { node: [null, inactive], default: "./fallback.cjs" },
"#null-last": [[], null],
"#empty-last": [null, []],
"#invalid": {
node: ["../outside.cjs", inactive],
default: "./fallback.cjs",
},
"#unmatched": [inactive],
"#unmatched-nested": [
[inactive, { "rea-inactive": "./inactive.cjs" }],
],
"#unmatched-active": { node: [inactive] },
},
}),
"main.cjs": "module.exports = 1;",
"fallback.cjs": "module.exports = 1;",
});
const inventoried = inventory(contents);
for (const [specifier, errorCode, status, limitation] of [
[
"#empty-direct",
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
"external",
"an empty imports target array",
],
[
"#empty",
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
"external",
"an empty imports target array",
],
[
"#null",
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
"external",
"an explicit null imports target",
],
[
"#null-last",
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
"external",
"an explicit null imports target",
],
[
"#empty-last",
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
"external",
"an empty imports target array",
],
["#invalid", "ERR_INVALID_PACKAGE_TARGET", "rejected", "../outside.cjs"],
[
"#unmatched",
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
"external",
"it declares browser.",
],
[
"#unmatched-nested",
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
"external",
"it declares browser, rea-inactive.",
],
[
"#unmatched-active",
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
"external",
"it declares node, browser.",
],
] as const) {
expect(
(await nodeRequireTarget(join(root, "main.cjs"), specifier)).error_code,
).toBe(errorCode);
expect((await nodeImportTarget(root, specifier)).error_code).toBe(
errorCode,
);
for (const moduleKind of ["require", "import"] as const) {
const result = resolveAlias(
inventoried,
specifier,
"main.cjs",
moduleKind,
);
expect(result).toMatchObject({
resolution_status: status,
resolved_path: null,
});
expect(result.limitations.join(" "), specifier).toContain(limitation);
}
}
});
});
describe("package import target arrays compared with Node", () => {
it("skips invalid parent, absolute, and URL targets before an exact fallback", async () => {
const root = await createTestTempDirectory("rea-import-alias-fallback-");
const imports = {
"#parent": ["../outside.cjs", "./fallback.cjs"],
"#absolute": { node: [["/outside.cjs"], "./fallback.cjs"] },
"#url": {
import: ["https://example.invalid/outside.cjs", "./fallback.cjs"],
require: ["file:///outside.cjs", "./fallback.cjs"],
},
};
const contents = await writeTree(root, {
"package.json": JSON.stringify({ imports }),
"main.cjs": "module.exports = 1;",
"fallback.cjs": "module.exports = 1;",
});
const inventoried = inventory(contents);
for (const specifier of Object.keys(imports)) {
const required = await nodeRequireTarget(
join(root, "main.cjs"),
specifier,
);
expect(required.error_code).toBeNull();
expect(posixRelative(root, required.target ?? "")).toBe("fallback.cjs");
const imported = await nodeImportTarget(root, specifier);
expect(imported.error_code).toBeNull();
expect(posixRelative(root, fileURLToPath(imported.target ?? ""))).toBe(
"fallback.cjs",
);
for (const moduleKind of ["require", "import"] as const)
expect(
resolveAlias(inventoried, specifier, "main.cjs", moduleKind),
).toMatchObject({
declared_path: specifier,
resolution_status: "resolved",
resolved_path: "fallback.cjs",
});
}
});
it("preserves invalid, null, and unsupported-package outcomes in arrays", async () => {
const root = await createTestTempDirectory(
"rea-import-alias-fallback-refuse-",
);
const contents = await writeTree(root, {
"package.json": JSON.stringify({
imports: {
"#invalid": [null, "../outside.cjs"],
"#blocked": ["../outside.cjs", null],
"#package": ["fixture", "./fallback.cjs"],
},
}),
"main.cjs": "module.exports = 1;",
"fallback.cjs": "module.exports = 1;",
"node_modules/fixture/package.json": JSON.stringify({
name: "fixture",
main: "index.cjs",
}),
"node_modules/fixture/index.cjs": "module.exports = 2;",
});
const inventoried = inventory(contents);
for (const [specifier, errorCode, resolutionStatus, reason] of [
["#invalid", "ERR_INVALID_PACKAGE_TARGET", "rejected", "../outside.cjs"],
[
"#blocked",
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
"external",
"explicit null",
],
] as const) {
const required = await nodeRequireTarget(
join(root, "main.cjs"),
specifier,
);
expect(required.error_code).toBe(errorCode);
expect((await nodeImportTarget(root, specifier)).error_code).toBe(
errorCode,
);
for (const moduleKind of ["require", "import"] as const) {
const result = resolveAlias(
inventoried,
specifier,
"main.cjs",
moduleKind,
);
expect(result).toMatchObject({
resolution_status: resolutionStatus,
resolved_path: null,
});
expect(result.limitations.join(" ")).toContain(reason);
}
}
const required = await nodeRequireTarget(
join(root, "main.cjs"),
"#package",
);
expect(posixRelative(root, required.target ?? "")).toBe(
"node_modules/fixture/index.cjs",
);
const imported = await nodeImportTarget(root, "#package");
expect(imported.error_code).toBeNull();
expect(posixRelative(root, fileURLToPath(imported.target ?? ""))).toBe(
"node_modules/fixture/index.cjs",
);
for (const moduleKind of ["require", "import"] as const) {
const result = resolveAlias(
inventoried,
"#package",
"main.cjs",
moduleKind,
);
expect(result).toMatchObject({
resolution_status: "external",
resolved_path: null,
});
expect(result.limitations.join(" ")).toContain(
"External-package import targets remain unresolved",
);
}
});
});
describe("package import aliases compared with Node", () => {
it("matches Node require and import for an exact root alias", async () => {
const root = await createTestTempDirectory("rea-import-alias-root-");
const files = {
"package.json": JSON.stringify({
name: "app",
imports: { "#config": "./config.cjs" },
}),
"main.cjs": 'module.exports = require("#config");',
"config.cjs": "module.exports = 'config.cjs';",
};
const contents = await writeTree(root, files);
const inventoried = inventory(contents);
const required = await nodeRequireTarget(join(root, "main.cjs"), "#config");
expect(posixRelative(root, required.target ?? "")).toBe("config.cjs");
expect(
resolveAlias(inventoried, "#config", "main.cjs", "require"),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "config.cjs",
});
const imported = await nodeImportTarget(root, "#config");
expect(imported.error_code).toBeNull();
expect(
resolveAlias(inventoried, "#config", "main.cjs", "import"),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "config.cjs",
});
});
it("matches Node when a nested package has its own imports map", async () => {
const root = await createTestTempDirectory("rea-import-alias-nested-");
const files = {
"package.json": JSON.stringify({
name: "app",
imports: { "#config": "./root.cjs" },
}),
"root.cjs": "module.exports = 'root';",
"node_modules/fixture/package.json": JSON.stringify({
name: "fixture",
imports: { "#config": "./local.cjs" },
}),
"node_modules/fixture/index.cjs": 'module.exports = require("#config");',
"node_modules/fixture/local.cjs": "module.exports = 'local';",
};
const contents = await writeTree(root, files);
const inventoried = inventory(contents);
const nested = await nodeRequireTarget(
join(root, "node_modules/fixture/index.cjs"),
"#config",
);
expect(posixRelative(root, nested.target ?? "")).toBe(
"node_modules/fixture/local.cjs",
);
expect(
resolveAlias(
inventoried,
"#config",
"node_modules/fixture/index.cjs",
"require",
),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "node_modules/fixture/local.cjs",
});
const fromRoot = await nodeRequireTarget(join(root, "root.cjs"), "#config");
expect(posixRelative(root, fromRoot.target ?? "")).toBe("root.cjs");
expect(
resolveAlias(inventoried, "#config", "root.cjs", "require"),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "root.cjs",
});
});
it("matches Node when a nested package does not define the alias", async () => {
const root = await createTestTempDirectory("rea-import-alias-scope-");
const files = {
"package.json": JSON.stringify({
name: "app",
imports: { "#config": "./root.cjs" },
}),
"root.cjs": "module.exports = 'root';",
"node_modules/fixture/package.json": JSON.stringify({
name: "fixture",
}),
"node_modules/fixture/index.cjs": 'module.exports = require("#config");',
};
await writeTree(root, files);
const nested = await nodeRequireTarget(
join(root, "node_modules/fixture/index.cjs"),
"#config",
);
expect(nested.target).toBeNull();
// CJS reports MODULE_NOT_FOUND when the nested package.json has no
// `imports` field at all; it still does not inherit the ancestor map.
expect(nested.error_code).toBe("MODULE_NOT_FOUND");
const outcome = resolveAlias(
inventory(new Map(Object.entries(files))),
"#config",
"node_modules/fixture/index.cjs",
"require",
);
expect(outcome).toMatchObject({
resolution_status: "external",
resolved_path: null,
});
expect(outcome.limitations.join(" ")).toContain(
"node_modules/fixture/package.json",
);
});
});
describe("package import alias refusals compared with Node", () => {
it("matches Node refusal for a missing key, explicit null, and reserved specifier", async () => {
const root = await createTestTempDirectory("rea-import-alias-refuse-");
const files = {
"package.json": JSON.stringify({
name: "app",
imports: {
"#config": "./config.cjs",
"#blocked": null,
"#": "./config.cjs",
"#/": "./config.cjs",
"#config/": "./config.cjs",
},
}),
"main.cjs": "module.exports = 1;",
"config.cjs": "module.exports = 1;",
};
await writeTree(root, files);
const inventoried = inventory(new Map(Object.entries(files)));
const missing = await nodeRequireTarget(join(root, "main.cjs"), "#missing");
expect(missing.error_code).toBe("ERR_PACKAGE_IMPORT_NOT_DEFINED");
expect(
resolveAlias(inventoried, "#missing", "main.cjs", "require"),
).toMatchObject({ resolution_status: "external", resolved_path: null });
const blocked = await nodeRequireTarget(join(root, "main.cjs"), "#blocked");
expect(blocked.error_code).toBe("ERR_PACKAGE_IMPORT_NOT_DEFINED");
expect(
resolveAlias(inventoried, "#blocked", "main.cjs", "require"),
).toMatchObject({ resolution_status: "external", resolved_path: null });
for (const specifier of ["#", "#/", "#config/"]) {
const reserved = await nodeRequireTarget(
join(root, "main.cjs"),
specifier,
);
expect(reserved.error_code).toBe("ERR_INVALID_MODULE_SPECIFIER");
expect((await nodeImportTarget(root, specifier)).error_code).toBe(
"ERR_INVALID_MODULE_SPECIFIER",
);
for (const moduleKind of ["require", "import"] as const)
expect(
resolveAlias(inventoried, specifier, "main.cjs", moduleKind),
).toMatchObject({ resolution_status: "rejected", resolved_path: null });
}
});
it("matches Node when an import condition selects a different exact file", async () => {
const root = await createTestTempDirectory("rea-import-alias-cond-");
const files = {
"package.json": JSON.stringify({
name: "app",
type: "module",
imports: {
"#config": {
import: "./config.mjs",
require: "./config.cjs",
},
},
}),
"main.cjs": 'module.exports = require("#config");',
"config.cjs": "export default 'cjs'; module.exports = 'cjs';",
"config.mjs": "export default 'mjs';",
};
await writeTree(root, files);
const inventoried = inventory(new Map(Object.entries(files)));
const required = await nodeRequireTarget(join(root, "main.cjs"), "#config");
expect(posixRelative(root, required.target ?? "")).toBe("config.cjs");
expect(
resolveAlias(inventoried, "#config", "main.cjs", "require"),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "config.cjs",
});
const imported = await nodeImportTarget(root, "#config");
expect(imported.error_code).toBeNull();
expect(imported.target ?? "").toContain("config.mjs");
expect(
resolveAlias(inventoried, "#config", "main.cjs", "import"),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "config.mjs",
});
});
});
+2
View File
@@ -50,6 +50,8 @@ const contract: ToolContract = {
accessesNetwork: false,
changesUiState: false,
mayDiscardData: false,
executesForeignCode: false,
mutatesDevice: false,
idempotent: true,
},
annotations: {
+15 -1
View File
@@ -73,7 +73,7 @@ function expectKnownAuthorityHints(tools: readonly ToolSchemas[]): void {
},
annotate_native_function: {
readOnlyHint: false,
destructiveHint: false,
destructiveHint: true,
idempotentHint: true,
openWorldHint: true,
},
@@ -102,8 +102,22 @@ function expectKnownAuthorityHints(tools: readonly ToolSchemas[]): void {
openWorldHint: false,
},
capture_process_scenario: {
readOnlyHint: false,
destructiveHint: true,
openWorldHint: true,
},
observe_native_calls: {
readOnlyHint: false,
destructiveHint: true,
},
uninstall_adb_package: {
readOnlyHint: false,
destructiveHint: true,
},
start_adb_app: {
readOnlyHint: false,
destructiveHint: true,
},
export_evidence_bundle: {
readOnlyHint: false,
destructiveHint: true,
@@ -0,0 +1,131 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it as test, onTestFinished } from "vitest";
import { androidResultSchemas } from "../../../src/domain/android/androidAnalysis.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import {
createJadxProtocolFixture,
verifyJadxFixtureCleanup,
} from "../../fixtures/android/jadx.js";
const INVENTORY_CLASS_COUNT = 7096;
/** Count inventoried names across raw call records: MCP pages ride in text content. */
const rawInventoryNames = (raw: unknown): number => {
const calls =
(
raw as {
calls?: {
operation: string;
response: { content?: { text?: string }[] };
}[];
}
).calls ?? [];
return calls
.flatMap((call) => call.response.content ?? [])
.map((entry) =>
entry.text === undefined ? {} : (JSON.parse(entry.text) as unknown),
)
.filter((page) => Array.isArray((page as { items?: unknown[] }).items))
.flatMap((page) => (page as { items: unknown[] }).items).length;
};
test("delivers bounded search_android_classes Evidence while retaining the complete inventory", async () => {
const { provider, apk, launches } = await createJadxProtocolFixture(
"normal",
undefined,
{ classCount: INVENTORY_CLASS_COUNT - 1 },
);
const session = createTestBinarySession(() => {
throw new Error("APK analysis must not acquire a deep binary provider");
});
const server = createServer(
{ kind: "session", session },
{ androidAnalysis: provider },
);
const client = new Client({
name: "android-search-inventory-budget",
version: "1",
});
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const search = async (query: string) =>
parseEvidence(
(
await client.callTool({
name: "search_android_classes",
arguments: { path: apk, query },
})
).structuredContent,
);
const single = await search("Target");
expect(
androidResultSchemas.search_android_classes.parse(single.normalized_result),
).toMatchObject({
query: "Target",
total_classes: INVENTORY_CLASS_COUNT,
matches: ["fixture.Target"],
coverage: "complete",
});
// The inline raw record keeps the pagination audit, not the class names.
const singleRaw = JSON.stringify(single.raw_result);
expect(singleRaw).not.toContain("fixture.Class");
expect(singleRaw).toContain("items_omitted");
expect(Buffer.byteLength(JSON.stringify(single))).toBeLessThan(32 * 1024);
// The complete inventory stays locally retrievable through the retained record.
const completeId = single.evidence_links[0];
expect(completeId).toBeDefined();
expect(completeId).toBe(
(single.raw_result as { complete_evidence_id: string })
.complete_evidence_id,
);
const complete = session.evidenceById(completeId as string);
expect(complete).toBeDefined();
expect(complete?.operation).toBe("search_android_classes");
expect(rawInventoryNames(complete?.raw_result)).toBe(INVENTORY_CLASS_COUNT);
expect(JSON.stringify(complete?.raw_result)).toContain("fixture.Class7094");
const empty = await search("fixture.Missing");
expect(
androidResultSchemas.search_android_classes.parse(empty.normalized_result),
).toMatchObject({
query: "fixture.Missing",
total_classes: INVENTORY_CLASS_COUNT,
matches: [],
coverage: "complete",
});
expect(JSON.stringify(empty.raw_result)).not.toContain("fixture.Class");
await client.close();
await server.close();
await verifyJadxFixtureCleanup(launches);
});
test("keeps the complete search inventory inline without a retaining session", async () => {
const { service, apk, launches, provider } = await createJadxProtocolFixture(
"normal",
undefined,
{ classCount: INVENTORY_CLASS_COUNT - 1 },
);
const result = await service.execute("search_android_classes", {
path: apk,
query: "Target",
});
if (!result.ok) throw result.error;
// Complete CLI JSON output keeps the full raw provider inventory.
expect(rawInventoryNames(result.value.raw_result)).toBe(
INVENTORY_CLASS_COUNT,
);
await provider.close();
await verifyJadxFixtureCleanup(launches);
});
+97 -1
View File
@@ -8,7 +8,10 @@ import {
runOwnedCommand,
} from "../../../src/process/OwnedCommand.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
import {
cleanupOwnedProcessGroup,
type ProcessCleanupResult,
} from "../../../src/process/ProcessOwnership.js";
import { prepareProcessOwnershipInspection } from "../../../src/process/ProcessOwnershipObservation.js";
import { waitForProviderProcessReady } from "../../fixtures/providerProcess.js";
@@ -186,6 +189,99 @@ it("returns a timeout for a running process after independent cleanup", async ()
).rejects.toMatchObject({ reason: "timeout", cleanupFailure: null });
});
it.skipIf(process.platform === "win32").each(["cancelled", "timeout"] as const)(
"retains the real per-member cleanup ledger after %s and settles after cooperative exit",
async (reason) => {
const childScript =
'process.stdin.once("data", () => process.exit(0)); process.stdout.write("child-ready\\n")';
const request = {
...command(`
const { spawn } = require("node:child_process");
const child = spawn(process.execPath, ["-e", ${JSON.stringify(childScript)}], {
env: { ...process.env, REA_PROCESS_RUN_ID: "different-child-owner" },
stdio: ["pipe", "inherit", "inherit"],
});
const release = () => child.stdin.end("release");
process.stdin.once("data", release);
const failsafe = setTimeout(release, 10000);
child.once("exit", () => { clearTimeout(failsafe); process.stdin.destroy(); });
`),
stdin: "pipe" as const,
};
const controller = new AbortController();
let launched:
| Awaited<ReturnType<typeof spawnOwnedProviderProcess>>
| undefined;
let cleanup: ProcessCleanupResult | undefined;
let failure: OwnedCommandFailure | undefined;
try {
await runOwnedCommand(
request,
{ timeoutMs: 2000, diagnosticBytes: 1024 },
{
signal: controller.signal,
launcher: async (input) => {
const acquired = await spawnOwnedProviderProcess(input);
launched = acquired;
acquired.process.stdout?.on("data", (chunk: Buffer) => {
if (
reason === "cancelled" &&
chunk.toString().includes("child-ready")
)
controller.abort();
});
return {
...acquired,
cleanup: async () => {
const observed = await cleanupOwnedProcessGroup(
acquired.ownership,
);
cleanup ??= observed;
return observed;
},
};
},
},
).catch((cause: unknown) => {
if (!(cause instanceof OwnedCommandFailure)) throw cause;
failure = cause;
});
if (failure === undefined || launched === undefined)
throw new Error(
"The acquired command must retain its failed cleanup owner",
);
expect(failure.reason).toBe(reason);
expect(failure.snapshot?.stdout.text).toContain("child-ready");
expect(cleanup).toMatchObject({
cleaned: false,
failures: [expect.objectContaining({ reason: "run-token-mismatch" })],
});
expect(failure.cleanupResult).toEqual(cleanup);
expect(failure.resources).toEqual(
expect.arrayContaining([request.runId]),
);
// An unresolved member does not grant authority to signal the shared group.
const acquiredPid = launched.ownership.leaderPid;
expect(() => process.kill(acquiredPid, 0)).not.toThrow();
if (cleanup?.cleaned === false) {
for (const member of cleanup.failures ?? []) {
expect(() => process.kill(member.pid, 0)).not.toThrow();
expect(failure.cleanupFailure).toContain(String(member.pid));
}
}
} finally {
// Release through the fixture's acquired input channel, never by an unverified PID.
launched?.process.stdin?.end("release");
if (failure?.cleanupOwner !== undefined) {
expect(await failure.cleanupOwner.waitForOutputClose(5000)).toBe(true);
expect(await failure.cleanupOwner.stop()).toEqual({
status: "verified-cleanup",
});
}
}
},
);
it("honors cancellation during cleanup after a successful command", async () => {
const controller = new AbortController();
await expect(
@@ -358,6 +358,57 @@ describe("provider process output and cleanup primitives", () => {
});
});
it("retains member failures and sweep uncertainty from a failed cleanup recheck", async () => {
const child = spawnProviderProcessFixture("stubborn");
await waitForProviderProcessReady(child);
const pid = child.pid;
if (pid === undefined) {
await stopProviderProcessFixture(child);
throw new Error("The acquired ready fixture must have a process ID");
}
const failed = {
cleaned: false as const,
reason: "fixture identity unavailable during recheck",
failures: [
{
pid,
reason: "process-identity-unavailable" as const,
diagnostic: "fixture identity reader unavailable",
},
],
unverified: [
{ pid: 777, diagnostic: "fixture foreign process token unavailable" },
],
};
let attempts = 0;
let release = false;
const supervisor = new ProviderProcessSupervisor({
process: child,
ownsProcessLifetime: true,
cleanup: async () => {
if (release) child.kill("SIGKILL");
attempts += 1;
return release || attempts === 1
? { cleaned: true as const, signaled: release }
: failed;
},
});
try {
await expect(supervisor.stop({ killGraceMs: 20 })).resolves.toEqual({
status: "incomplete",
reason: failed.reason,
cleanupResult: failed,
});
expect(child.exitCode).toBeNull();
release = true;
await expect(supervisor.stop()).resolves.toEqual({
status: "verified-cleanup",
});
} finally {
await stopProviderProcessFixture(child);
}
});
describe("provider process host injection", () => {
it("uses injected host platform and environment when spawning", async () => {
const spawned = await spawnOwnedProviderProcess({
+11 -1
View File
@@ -10,10 +10,20 @@ const server = new McpServer({
version:
mode === "empty-server-identity" ? "" : mode === "version" ? "99.0.0" : "1",
});
const requestedCount = Number.parseInt(
process.env.REA_FAKE_JADX_CLASS_COUNT ?? "",
10,
);
const generatedCount =
Number.isInteger(requestedCount) && requestedCount >= 0
? requestedCount
: mode === "large-inventory"
? 9000
: 400;
const classes = [
"fixture.Target",
...Array.from(
{ length: mode === "large-inventory" ? 9000 : 400 },
{ length: generatedCount },
(_, index) => `fixture.Class${index}`,
),
];
+10 -1
View File
@@ -27,6 +27,7 @@ const fixture = fileURLToPath(new URL("./jadx-mcp.mjs", import.meta.url));
export const createJadxProtocolFixture = async (
mode = "normal",
cleanupFailure?: () => boolean,
inventory?: { readonly classCount?: number },
) => {
const root = await createTestTempDirectory("rea-android-boundary-");
const apk = join(root, "fixture.apk");
@@ -64,7 +65,15 @@ export const createJadxProtocolFixture = async (
command: process.execPath,
arguments: [fixture],
expectedCommand: process.execPath,
env: { ...options.env, REA_FAKE_JADX_MODE: mode },
env: {
...options.env,
REA_FAKE_JADX_MODE: mode,
...(inventory?.classCount === undefined
? {}
: {
REA_FAKE_JADX_CLASS_COUNT: String(inventory.classCount),
}),
},
});
launches.push({
runId: options.runId,