Files
reverse-engineering-anything/tests/boundary/inspector/javascriptRuntimeObservation.test.ts
T
morluto 1f24b3fa57 feat(evidence)!: name the Evidence subject by its target identity (format revision 2) (#11416)
* feat(evidence)!: name the Evidence subject by its target identity (format revision 2)

The Evidence subject carries subject.identity (kind, sha256, format,
architecture, selection) and the Evidence ID commits to it, so raw/DOL
entry points and ESP flash offsets of the same bytes are different
subjects. Every record declares evidence_format: 2; revision 1 bundles,
standalone records and snapshots are refused with the recreate guidance.
binaryTargetIdentity is the one projection of an open target, used by
Evidence and snapshot comparison.

BREAKING CHANGE: Evidence format revision 2. Evidence IDs commit to the
subject's target identity (subject.identity, including the raw/DOL entry
point or ESP flash offsets), and every record declares evidence_format: 2.
Evidence bundles, records and analysis snapshots from earlier releases are
refused; recreate the observations with this release.

* refactor(analysis-view): read parent subjects through the Evidence identity accessors (#11423)

Analysis views compare their parent's file identity (evidenceFileTarget)
and take path and digest from evidenceSubjectTarget instead of reading
the subject's digest, format and architecture members, which duplicate
subject.identity until they are removed. A counted guard
(evidence-subject-declaration-read) keeps new direct reads out and
records the 20 remaining files.

* fix(evidence): carry format refusals through Evidence readers and bind target selections

- safeParseEvidence/safeParseImmutableEvidence return the format refusal as
  an expected failure; every consumer maps it to the one integrity refusal
  with the recreate guidance. An unmarked object is an earlier record only
  when it has every member records have always carried.
- ArtifactProvider inventory roots and provider subjects that name the
  target's own bytes carry the target's selection (ESP flash offsets).
- Snapshot rows bind only Evidence whose identity, selection included,
  matches the snapshot target.
- Entry-point selections use the raw-binary entry point form.

* fix(evidence): refuse unauthenticated or earlier-format records instead of reading them as absent

- recognizeEvidence (evidenceValidation) replaces tryParseEvidence: input
  without an evidence_id is not Evidence (ok(undefined)); a record that names
  one but fails authentication or is from another format revision is an
  EvidenceIntegrityError carrying the recreate guidance, never undefined.
- Direct analysis retains that refusal as a secondary failure instead of
  silently skipping source capture; cleanup projection, source-closure
  annotation and the flutter, debugger and release-exposure recoveries use
  the same owner (the last three previously read the unauthenticated schema).
- A desktop capture.json from an earlier format is refused with the recreate
  guidance instead of "not desktop application capture Evidence".

* fix(evidence): advertise revision 2 ledger examples and rank delivery omissions by serialized size

- The obligation ledger and reconstruction coverage examples named
  evidence_format 1, which revision 2 refuses; they now use
  EVIDENCE_FORMAT_REVISION.
- MCP delivery chose which unretained recovery to omit by a parsed-storage
  lower bound clipped at the response budget. Once revision 2 subjects made
  the source record's estimate cross the budget, both candidates tied at the
  clip and the smaller source was omitted ahead of the larger completed
  observation. Candidates are now ranked by serialized size, which is what
  the budget counts.

* refactor(native): compare function snapshots by their Evidence target identity (#11450)

Function snapshots carry the subject's file target identity instead of the
duplicated subject declaration. Call paths and function comparisons compare
targets through sameTargetIdentity, so the same bytes opened at a different
raw entry point or ESP flash offset no longer count as one coordinate space:
build_call_path refuses the mix, and compare_functions no longer matches
entries by address across selections. Structural candidates and native
function matching read the architecture and digest through
evidenceFileTarget.

Refs #11417

* refactor(artifacts): compare artifact and WASM summaries by their Evidence target identity (#11461)

Artifact comparison authenticates a summary against its retained inventory
through sameTargetIdentity and rebinds the alias with the whole target,
selection included, so a flash-selected inventory summary taken under an
alias path is no longer refused. WASM comparison, the analysis view
artifact projection and the inventory root check read the digest, format
and display path through the Evidence identity accessors.

Refs #11417

* refactor(evidence): read record subjects through the identity accessors in JS, managed, ledger and bundle readers (#11470)

JavaScript application graphs, runtime reconciliation, managed inspection
and native verification sources, the record summary filter, the ledger's
residual-unknown target and bundle scope selection read the subject digest,
format and display path through evidenceFileTarget and
evidenceSubjectDisplay. No comparison changes: each reader matches one
record's facts against its own payload or a caller filter.

Refs #11417

* refactor(evidence)!: name the Evidence subject only by its target identity (#11497)

* refactor(evidence)!: name the Evidence subject only by its target identity

The subject keeps `identity` and the display facts `name` and `local_path`.
The duplicated `digest`, `format` and `architecture` members are removed; the
format-owned declaration now validates the identity itself. Readers the type
checker found move to the owner accessors; untyped reads in verify scripts,
the efficiency harness and test matchers move to `subject.identity`. The
`evidence-subject-declaration-read` text guard and its baseline are deleted.

Fixes #11473
Refs #11417

BREAKING CHANGE: the Evidence subject no longer has `digest`, `format` or
`architecture`; read `subject.identity.sha256`, `subject.identity.format` and
`subject.identity.architecture`. A record that still carries them is refused.

* test(evidence): give the Flutter verifier fixture the identity subject and check the DOL declaration without the ID

* test(evidence): drop the removed subject members from the declaration matrix and tamper fixtures

* feat(evidence)!: give every Evidence record an explicit subject identity (#11536)

* feat(evidence)!: give every Evidence record an explicit subject identity

A producer that cannot name a file passes an `unknown` target identity
with a closed reason (derived-from-linked-evidence, not-observed,
unsupported-subject) instead of no subject. The subject is non-null;
unknown subjects have no display facts. The generic missing-subject
limitation and `subjectUnavailableReason` are removed; producer-specific
explanations are ordinary limitations. Comparison identity requires the
derived unknown, and null-subject consumers ask the owner accessors.

Refs #11417

BREAKING CHANGE: every Evidence record has a subject. A record without a
file target names `subject.identity` `{ "kind": "unknown", "reason": … }`
with `name` and `local_path` null, instead of `subject: null` and the
limitation "Artifact identity is unavailable for this observation.".
Their Evidence IDs change.

* fix(evidence): name explicit unknown subjects in JavaScript callers and keep a managed graph's file subject

The verification scripts are not type-checked, so five createEvidence
callers still passed undefined (or a missing first target) after the subject
became required. They now pass unknownTarget("not-observed").

A managed application graph chose the first present input subject. Every
subject is now present, so an unknown artifact subject hid a file subject on
the member or boundary Evidence. The graph now takes the first input subject
that names a file.

* test(evidence): assert the subject kind instead of a presence the type now guarantees

Every Evidence record has a subject after this change, so test guards and
assertions that checked it for null always passed. Each now checks that the
fixture subject names a file, or is removed where a later fileIdentity,
fileSubjectTarget or fileSubjectDisplay call already requires that. Non-null
assertions on Evidence subjects are removed; analysis-view inputs, whose
subject is optional, keep an undefined check.

* test(evidence): expect the Evidence subject format under its identity

Two boundary tests still matched subject.format, which slice 2e moved into
subject.identity. toMatchObject is not type-checked against the Evidence
shape, so they failed only when run (the signature test on macOS).
2026-11-16 06:28:01 +08:00

1050 lines
34 KiB
TypeScript

import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { describe, expect, test } from "vitest";
import { createJavaScriptRuntimeObservationEvidence } from "../../../src/application/javascript/JavaScriptRuntimeObservationEvidence.js";
import { createBrowserEvidence } from "../../../src/application/BrowserEvidence.js";
import {
listJavaScriptRuntimeTargets,
observeJavaScriptRuntime,
} from "../../../src/application/javascript/JavaScriptRuntimeObservationService.js";
import { reconcileJavaScriptRuntimeEvidence } from "../../../src/application/javascript/JavaScriptRuntimeReconciliationService.js";
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
import { V8_INSPECTOR_PROVIDER_IDENTITY } from "../../../src/inspector/providerIdentity.js";
import { V8InspectorProvider } from "../../../src/inspector/V8InspectorProvider.js";
import { JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE } from "../../../src/contracts/javascript/javascriptRuntimeReconciliationExample.js";
import type {
JavaScriptRuntimeObservation,
ObserveJavaScriptRuntimeInput,
} from "../../../src/domain/javascript/javascriptRuntimeObservation.js";
import {
javascriptRuntimeObservationSchema,
observeJavaScriptRuntimeInputSchema,
} from "../../../src/domain/javascript/javascriptRuntimeObservation.js";
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
import {
createEvidence,
evidenceSubjectInput,
} from "../../../src/domain/evidence.js";
import { javascriptRuntimeReconciliationResultSchema } from "../../../src/domain/javascript/javascriptRuntimeReconciliationSchemas.js";
import { parseRuntimeCapture } from "../../../src/domain/javascript/javascriptRuntimeReconciliationCaptureParsing.js";
import { startFakeV8Inspector } from "../../fixtures/inspector/fakeV8Inspector.js";
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
import { createNodeDiscoveryTempDirectory } from "../../fixtures/temporaryDirectory.js";
test("reports static-layer Evidence digest failure at its caller path", () => {
const layer = JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE.static_layers[0];
if (layer === undefined) throw new Error("Expected a static layer example");
const runtime = createJavaScriptRuntimeObservationEvidence(
"observe_javascript_runtime",
{
inspector_endpoint: "http://127.0.0.1:9229",
target_id: "example-v8-target",
runtime_kind: "electron-main",
observation_ms: 100,
},
runtimeObservation("/tmp/index.html", "/tmp/main.js"),
V8_INSPECTOR_PROVIDER_IDENTITY,
);
const result = reconcileJavaScriptRuntimeEvidence({
static_layers: [
{
...layer,
analysis: { ...layer.analysis, evidence_id: `ev_${"0".repeat(64)}` },
},
],
runtime_observations: [runtime],
});
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisInputError",
issues: [
{
path: ["static_layers", 0, "analysis", "evidence_id"],
reason: "invalid_value",
message: expect.stringMatching(/semantic identifier.*not match/iu),
},
],
},
});
});
test("reports browser origin scope mismatch at the caller parameter path", async () => {
const browser = await startFakeCdpBrowser();
try {
const provider = new CdpBrowserProvider();
const input = inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 0,
});
const observed = await provider.inspectPage(input);
if (!observed.ok) throw observed.error;
const evidence = createBrowserEvidence(
"inspect_web_page",
input,
{ source: jsonValueSchema.parse(observed.value), facts: observed.value },
provider.identity(),
);
const invalidEvidence = createEvidence(
evidenceSubjectInput(evidence.subject),
evidence.provider,
{
predicateType: evidence.predicate_type,
operation: evidence.operation,
parameters: { ...evidence.parameters, allowed_origins: [] },
result: evidence.normalized_result,
confidence: evidence.confidence,
authority: evidence.authority,
environment: evidence.environment,
limitations: evidence.limitations,
},
);
const result = reconcileJavaScriptRuntimeEvidence({
static_layers: JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE.static_layers,
runtime_observations: [invalidEvidence],
});
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisInputError",
issues: [
{
path: ["runtime_observations", 0, "parameters", "allowed_origins"],
reason: "invalid_value",
message: expect.stringMatching(
/target.*outside.*recorded origin scope/i,
),
},
],
},
});
} finally {
await browser.close();
}
});
describe("Inspector execution-context lifecycle metadata", () => {
test.each([
[
"Runtime.executionContextDestroyed",
{ executionContextId: 1 },
"destroyed",
],
["Runtime.executionContextsCleared", {}, "cleared"],
] as const)(
"preserves observed context metadata after %s",
async (method, params, state) => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
runtimeEvents: [
{
method: "Runtime.executionContextCreated",
params: {
context: {
id: 1,
origin: "https://context.example",
name: "worker#one",
},
},
},
{ method, params },
],
});
try {
const result = await new V8InspectorProvider().observe(
observeInput(fake.endpoint, fake.targetId, "node"),
);
if (!result.ok) throw result.error;
expect(result.value.execution_contexts).toEqual([
{
context_key: "context_0",
execution_context_id: 1,
state,
name: "worker#one",
origin: "https://context.example",
},
]);
} finally {
await fake.close();
}
},
);
test("retains each context lifetime after an ID is reused", async () => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
runtimeEvents: [
{
method: "Runtime.executionContextCreated",
params: {
context: {
id: 1,
origin: "https://old.example",
name: "old context",
},
},
},
{
method: "Runtime.executionContextDestroyed",
params: { executionContextId: 1 },
},
{
method: "Runtime.executionContextCreated",
params: { context: { id: 1, origin: "", name: "" } },
},
{
method: "Runtime.executionContextDestroyed",
params: { executionContextId: 2 },
},
],
});
try {
const result = await new V8InspectorProvider().observe(
observeInput(fake.endpoint, fake.targetId, "node"),
);
if (!result.ok) throw result.error;
expect(result.value.execution_contexts).toEqual([
{
context_key: "context_0",
execution_context_id: 1,
state: "destroyed",
name: "old context",
origin: "https://old.example",
},
{
context_key: "context_1",
execution_context_id: 1,
state: "created",
name: "",
origin: "",
},
{
context_key: "context_2",
execution_context_id: 2,
state: "destroyed",
name: null,
origin: null,
},
]);
} finally {
await fake.close();
}
});
});
describe("Inspector execution-context ID validation", () => {
test.each([
["malformed", "2", "1"],
["valid", 2, 1],
] as const)(
"accounts for %s context IDs in lifecycle events",
async (mode, createdId, destroyedId) => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
runtimeEvents: [
{
method: "Runtime.executionContextCreated",
params: { context: { id: 1, name: "main", origin: "" } },
},
{
method: "Runtime.executionContextCreated",
params: { context: { id: createdId, name: "worker", origin: "" } },
},
{
method: "Runtime.executionContextDestroyed",
params: { executionContextId: destroyedId },
},
],
scriptEvents: [],
});
try {
const result = await new V8InspectorProvider().observe(
observeInput(fake.endpoint, fake.targetId, "node"),
);
if (!result.ok) throw result.error;
const invalidContextUnknowns = result.value.unknowns.filter((text) =>
text.includes("malformed execution-context ID"),
);
expect(result.value.capture).toMatchObject({
events_observed: 3,
events_retained: 3,
events_dropped: 0,
truncated: false,
});
if (mode === "malformed") {
expect(result.value.execution_contexts).toEqual([
{
context_key: "context_0",
execution_context_id: 1,
state: "created",
name: "main",
origin: "",
},
]);
expect(invalidContextUnknowns).toEqual([
"2 execution-context lifecycle events with a missing or malformed execution-context ID were excluded; the affected contexts' lifecycle state is unknown.",
]);
return;
}
expect(result.value.execution_contexts).toEqual([
{
context_key: "context_0",
execution_context_id: 1,
state: "destroyed",
name: "main",
origin: "",
},
{
context_key: "context_1",
execution_context_id: 2,
state: "created",
name: "worker",
origin: "",
},
]);
expect(invalidContextUnknowns).toEqual([]);
} finally {
await fake.close();
}
},
);
});
test("rejects unknown runtime observation fields", () => {
expect(
observeJavaScriptRuntimeInputSchema.safeParse({
inspector_endpoint: "http://127.0.0.1:9229",
target_id: "target-1",
unknown_field: true,
}).success,
).toBe(false);
});
test("returns every target exposed by the selected Inspector endpoint inline", async () => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
additionalTargetCount: 205,
});
try {
const listed = await new V8InspectorProvider().listTargets({
inspector_endpoint: fake.endpoint,
});
if (!listed.ok) throw listed.error;
expect(listed.value.targets).toHaveLength(206);
expect(listed.value.targets[0]?.target_id).toBe(fake.targetId);
} finally {
await fake.close();
}
});
test.each([
{ label: "omitted", attached: undefined, expected: null },
{ label: "explicitly detached", attached: false, expected: false },
] as const)(
"preserves $label V8 attachment state through listing and observation",
async ({ attached, expected }) => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
...(attached === undefined ? {} : { attached }),
});
try {
const provider = new V8InspectorProvider();
const listed = await provider.listTargets({
inspector_endpoint: fake.endpoint,
});
if (!listed.ok) throw listed.error;
expect(listed.value.targets[0]?.attached).toBe(expected);
if (expected === null)
expect(
listed.value.limitations.some((item) =>
item.includes("attachment state"),
),
).toBe(true);
const observed = await provider.observe(
observeInput(fake.endpoint, fake.targetId, "node"),
);
if (!observed.ok) throw observed.error;
expect(observed.value.target.attached).toBe(expected);
if (expected === null)
expect(
observed.value.limitations.some((item) =>
item.includes("attachment state"),
),
).toBe(true);
} finally {
await fake.close();
}
},
);
test("rejects a V8 target explicitly marked attached", async () => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
attached: true,
});
try {
const result = await new V8InspectorProvider().observe(
observeInput(fake.endpoint, fake.targetId, "node"),
);
expect(result).toMatchObject({
ok: false,
error: { reason: "target_not_allowed" },
});
expect(fake.commands).toEqual([]);
} finally {
await fake.close();
}
});
test("includes targets outside the old caller root filter", async () => {
const fixture = await runtimeFixture();
const outside = await temporaryFile("outside.js");
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
additionalTargetUrl: pathToFileURL(outside).href,
});
try {
const result = await new V8InspectorProvider().listTargets({
inspector_endpoint: fake.endpoint,
});
if (!result.ok) throw result.error;
expect(result.value.targets).toHaveLength(2);
expect(result.value.targets.map(({ location }) => location)).toContainEqual(
expect.objectContaining({ file_path: outside }),
);
} finally {
await fake.close();
}
});
test("captures complete metadata with two enable commands", async () => {
const fixture = await runtimeFixture();
const outside = await temporaryFile("secret.js");
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
scriptUrls: [
pathToFileURL(fixture.entry).href,
"node:fs",
pathToFileURL(outside).href,
],
});
try {
const result = await new V8InspectorProvider().observe(
observeInput(fake.endpoint, fake.targetId, "node"),
);
if (!result.ok) throw result.error;
expect(result.value.scripts.items).toHaveLength(3);
expect(result.value.scripts.excluded.unsupported_location).toBe(0);
expect(result.value.execution_contexts).toEqual([
{
context_key: "context_0",
execution_context_id: 1,
state: "created",
name: "node[fixture]",
origin: "",
},
]);
expect(new Set(fake.commands.map(({ method }) => method))).toEqual(
new Set(["Runtime.enable", "Debugger.enable"]),
);
expect(result.value.scripts.items).toContainEqual(
expect.objectContaining({
location: expect.objectContaining({ file_path: outside }),
}),
);
expect(result.value.unavailable_without_instrumentation).toContain(
"Electron IPC messages and handlers",
);
} finally {
await fake.close();
}
});
test("excludes an Electron main target that reports only bare file://", async () => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: "file://",
scriptUrls: [pathToFileURL(fixture.entry).href],
});
try {
const provider = new V8InspectorProvider();
const listed = await provider.listTargets({
inspector_endpoint: fake.endpoint,
});
if (!listed.ok) throw listed.error;
expect(listed.value.targets).toEqual([]);
const observed = await provider.observe(
observeInput(fake.endpoint, fake.targetId, "electron-main"),
);
expect(observed.ok).toBe(false);
if (observed.ok) return;
expect(observed.error.message).toMatch(/target/u);
} finally {
await fake.close();
}
});
test.each([
["node", "node"],
["electron-main", "node"],
["electron-preload", "page"],
["electron-renderer", "page"],
] as const)(
"admits declared %s only on its protocol target family",
async (runtimeKind, targetType) => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
targetType,
});
try {
const result = await new V8InspectorProvider().observe(
observeInput(fake.endpoint, fake.targetId, runtimeKind),
);
expect(result.ok).toBe(true);
} finally {
await fake.close();
}
},
);
describe("complete Inspector script hashes", () => {
test("keeps more than one hundred long script hashes distinct", async () => {
const fixture = await runtimeFixture();
const url = pathToFileURL(fixture.entry).href;
const prefix = "h".repeat(512);
const scriptHashes = Array.from(
{ length: 101 },
(_, index) => `${prefix}${String(index)}`,
);
const fake = await startFakeV8Inspector({
targetUrl: url,
scriptUrls: scriptHashes.map(() => url),
scriptHashes,
});
try {
const result = await new V8InspectorProvider().observe({
...observeInput(fake.endpoint, fake.targetId, "node"),
observation_ms: 1_000,
});
if (!result.ok) throw result.error;
expect(result.value.scripts.items).toHaveLength(scriptHashes.length);
expect(
new Set(result.value.scripts.items.map(({ cdp_hash }) => cdp_hash)),
).toEqual(new Set(scriptHashes));
} finally {
await fake.close();
}
});
});
describe("undeclared V8 runtime role", () => {
test("observes a target without inventing a runtime role", async () => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
targetType: "page",
});
try {
const input = observeInput(fake.endpoint, fake.targetId, "node");
delete input.runtime_kind;
const result = await new V8InspectorProvider().observe(input);
if (!result.ok) throw result.error;
expect(result.value.target).toMatchObject({
protocol_type: "page",
runtime_kind: "unknown",
runtime_kind_authority: "not-declared",
});
} finally {
await fake.close();
}
});
});
describe("V8 Inspector script retention", () => {
test("retains authorized script locations longer than the former byte ceiling", async () => {
const longUrl = `https://example.test/${"a".repeat(20_000)}`;
const fake = await startFakeV8Inspector({
targetUrl: longUrl,
scriptUrls: [longUrl],
});
try {
const input = {
...observeInput(fake.endpoint, fake.targetId, "node"),
};
const result = await new V8InspectorProvider().observe(input);
if (!result.ok) throw result.error;
expect(result.value.scripts.items).toHaveLength(1);
expect(result.value.scripts.items[0]?.location).toMatchObject({
kind: "url",
origin: "https://example.test",
sanitized_url: longUrl,
});
} finally {
await fake.close();
}
});
test("returns every authorized script beyond the former collection ceiling", async () => {
const fixture = await runtimeFixture();
const scriptUrls = [
pathToFileURL(fixture.entry).href,
...Array.from({ length: 2_004 }, () => pathToFileURL(fixture.entry).href),
];
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
scriptUrls,
});
try {
const input = {
...observeInput(fake.endpoint, fake.targetId, "node"),
observation_ms: 1_000,
};
const result = await new V8InspectorProvider().observe(input);
if (!result.ok) throw result.error;
expect(result.value.capture.truncated).toBe(false);
expect(result.value.capture.truncation_reasons).toEqual([]);
expect(result.value.capture.events_dropped).toBe(0);
expect(result.value.scripts.items).toHaveLength(scriptUrls.length);
} finally {
await fake.close();
}
});
});
describe("bounded V8 Inspector capture", () => {
test("bounds aggregate script and context metadata while retaining a useful partial capture", async () => {
const fixture = await runtimeFixture();
const url = pathToFileURL(fixture.entry).href;
const scriptHashes = Array.from(
{ length: 2_300 },
(_, index) => `${"h".repeat(4_096)}${String(index)}`,
);
const fake = await startFakeV8Inspector({
targetUrl: url,
scriptUrls: scriptHashes.map(() => url),
scriptHashes,
contextTransitionCount: 2_000,
});
try {
const result = await new V8InspectorProvider().observe({
...observeInput(fake.endpoint, fake.targetId, "node"),
observation_ms: 1_000,
});
if (!result.ok) throw result.error;
expect(result.value.capture.truncated).toBe(true);
expect(result.value.capture.truncation_reasons).toEqual([
"retained_metadata_budget_exceeded",
]);
expect(result.value.capture.events_dropped).toBeGreaterThan(0);
expect(result.value.capture.metadata_bytes_retained).toBeLessThanOrEqual(
8 * 1024 * 1024,
);
expect(result.value.capture.events_observed).toBeGreaterThan(
result.value.capture.events_retained,
);
expect(result.value.execution_contexts).toHaveLength(1);
} finally {
await fake.close();
}
});
test("rejects a CDP event larger than the configured transport payload budget", async () => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
oversizedEventBytes: 16 * 1024 * 1024,
});
try {
const result = await new V8InspectorProvider().observe(
observeInput(fake.endpoint, fake.targetId, "node"),
);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toMatchObject({
_tag: "BrowserObservationError",
reason: "payload_limit",
});
expect(result.error.userMessage).toContain("protocol budget");
} finally {
await fake.close();
}
});
});
describe("passive V8 Inspector evidence", () => {
test("produces deterministic Evidence through the service without grants", async () => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
});
try {
const input = observeInput(fake.endpoint, fake.targetId, "node");
const first = await observeJavaScriptRuntime(
new V8InspectorProvider(),
input,
);
const second = await observeJavaScriptRuntime(
new V8InspectorProvider(),
input,
);
expect(first.ok).toBe(true);
expect(second.ok).toBe(true);
if (!first.ok || !second.ok) return;
expect(second.value.evidence_id).toBe(first.value.evidence_id);
const listed = await listJavaScriptRuntimeTargets(
new V8InspectorProvider(),
{
inspector_endpoint: fake.endpoint,
},
);
expect(listed.ok).toBe(true);
} finally {
await fake.close();
}
});
test("reconciles V8 script presence with static Application Graph Evidence", () => {
const root = "/Applications/Example.app/Contents/Resources/app";
const observation = runtimeObservation(
`${root}/index.html`,
`${root}/renderer.js`,
);
const runtimeEvidence = createJavaScriptRuntimeObservationEvidence(
"observe_javascript_runtime",
{
inspector_endpoint: "http://127.0.0.1:9229",
target_id: "example-v8-target",
runtime_kind: "electron-main",
observation_ms: 100,
},
observation,
V8_INSPECTOR_PROVIDER_IDENTITY,
);
const reconciled = reconcileJavaScriptRuntimeEvidence({
static_layers: JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE.static_layers,
runtime_observations: [runtimeEvidence],
});
if (!reconciled.ok) throw reconciled.error;
const result = javascriptRuntimeReconciliationResultSchema.parse(
reconciled.value.evidence.normalized_result,
);
expect(result.runtime_captures[0]?.kind).toBe("v8-inspector");
expect(result.summary.runtime_scripts).toBe(1);
expect(result.summary.matched).toBeGreaterThan(0);
});
test("keeps unverified partial script URLs unresolved during reconciliation", () => {
const rawUrl = "file:///tmp/not-verified.js?caller-value=kept";
const resolvedObservation = runtimeObservation(
"/Applications/Example.app/Contents/Resources/app/index.html",
"/Applications/Example.app/Contents/Resources/app/renderer.js",
);
const resolvedScript = resolvedObservation.scripts.items[0];
if (resolvedScript === undefined)
throw new Error("Expected the runtime fixture to have one script");
const observation: JavaScriptRuntimeObservation = {
...resolvedObservation,
scripts: {
...resolvedObservation.scripts,
items: [
...resolvedObservation.scripts.items.map((script) => ({
...script,
location: {
kind: "unresolved" as const,
reported_url: rawUrl,
reason: "location-authorization-not-attempted" as const,
},
})),
{
...resolvedScript,
script_key: `v8_script_${"5".repeat(64)}`,
location: {
kind: "unresolved",
reported_url: "",
reason: "location-authorization-not-attempted",
},
cdp_hash: null,
length: 0,
},
],
},
};
const runtimeEvidence = createJavaScriptRuntimeObservationEvidence(
"observe_javascript_runtime",
{
inspector_endpoint: "http://127.0.0.1:9229",
target_id: "example-v8-target",
runtime_kind: "electron-main",
observation_ms: 100,
},
observation,
V8_INSPECTOR_PROVIDER_IDENTITY,
);
const reconciled = reconcileJavaScriptRuntimeEvidence({
static_layers: JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE.static_layers,
runtime_observations: [runtimeEvidence],
});
if (!reconciled.ok) throw reconciled.error;
const result = javascriptRuntimeReconciliationResultSchema.parse(
reconciled.value.evidence.normalized_result,
);
expect(result.summary.runtime_scripts).toBe(2);
expect(result.reconciliations).toContainEqual(
expect.objectContaining({
entity_kind: "script",
status: "unknown",
reason: "runtime-location-unresolved",
}),
);
const runtimeProperties = result.graph.nodes
.filter(({ kind }) => kind === "runtime-script-instance")
.flatMap(({ observations }) =>
observations.map(({ properties }) => properties),
);
expect(runtimeProperties).toContainEqual(
expect.objectContaining({ reported_url: rawUrl, cdp_hash: "v8-hash" }),
);
expect(runtimeProperties).toContainEqual(
expect.objectContaining({ reported_url: "", cdp_hash: null }),
);
});
});
test("keeps Inspector parse failures separate and preserves file URL script identity through reconciliation", async () => {
const fixture = await runtimeFixture();
const firstUrl = `${pathToFileURL(fixture.entry).href}?instance=1#first`;
const secondUrl = `${pathToFileURL(fixture.entry).href}?instance=2#second`;
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
scriptEvents: [
...[firstUrl, secondUrl].map((url, index) => ({
method: "Debugger.scriptParsed",
params: {
scriptId: String(index + 1),
url,
executionContextId: 1,
hash: "same-source-hash",
length: 42,
isModule: true,
},
})),
{
method: "Debugger.scriptFailedToParse",
params: { scriptId: "failed", url: firstUrl },
},
],
});
try {
const observed = await new V8InspectorProvider().observe(
observeInput(fake.endpoint, fake.targetId, "node"),
);
if (!observed.ok) throw observed.error;
expect(observed.value.scripts.items).toHaveLength(2);
expect(observed.value.scripts.items).toEqual(
expect.arrayContaining([
expect.objectContaining({
location: { kind: "file", file_path: fixture.entry },
reported_url: firstUrl,
}),
expect.objectContaining({
location: { kind: "file", file_path: fixture.entry },
reported_url: secondUrl,
}),
]),
);
expect(
new Set(observed.value.scripts.items.map(({ script_key }) => script_key))
.size,
).toBe(2);
expect(observed.value.scripts).toMatchObject({
parse_failed_total: 1,
excluded: {
unsupported_location: 0,
invalid_protocol_value: 0,
},
});
const evidence = createJavaScriptRuntimeObservationEvidence(
"observe_javascript_runtime",
{
inspector_endpoint: fake.endpoint,
target_id: fake.targetId,
runtime_kind: "node",
observation_ms: 100,
},
observed.value,
V8_INSPECTOR_PROVIDER_IDENTITY,
);
const reconciled = reconcileJavaScriptRuntimeEvidence({
static_layers: JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE.static_layers,
runtime_observations: [evidence],
});
if (!reconciled.ok) throw reconciled.error;
const result = javascriptRuntimeReconciliationResultSchema.parse(
reconciled.value.evidence.normalized_result,
);
const runtimeScripts = result.graph.nodes.filter(
(node) => node.kind === "runtime-script-instance",
);
const reportedUrls = runtimeScripts.flatMap((node) =>
node.observations
.map(({ properties }) => properties.reported_url)
.filter((url): url is string => typeof url === "string"),
);
expect(reportedUrls).toEqual(expect.arrayContaining([firstUrl, secondUrl]));
expect(new Set(reportedUrls).size).toBe(2);
const scriptKeys = runtimeScripts.flatMap((node) =>
node.identity.strategy === "runtime-instance"
? [node.identity.runtime_key]
: [],
);
expect(new Set(scriptKeys).size).toBe(2);
const parsedCapture = parseRuntimeCapture(evidence, [
"runtime_observations",
0,
]);
if (parsedCapture?.kind !== "v8-inspector")
throw new Error("Expected the Inspector Evidence to parse as V8 capture");
expect(
parsedCapture.inspection.completeness.unavailable_sections,
).not.toContain("scripts");
const withoutCount = {
...observed.value,
scripts: {
...observed.value.scripts,
},
};
delete (withoutCount.scripts as { parse_failed_total?: number })
.parse_failed_total;
expect(
javascriptRuntimeObservationSchema.safeParse(withoutCount).error?.issues,
).toMatchObject([{ path: ["scripts", "parse_failed_total"] }]);
} finally {
await fake.close();
}
});
test("keeps malformed scriptFailedToParse protocol values in the invalid count", async () => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
scriptEvents: [
{
method: "Debugger.scriptFailedToParse",
params: { url: pathToFileURL(fixture.entry).href },
},
],
});
try {
const observed = await new V8InspectorProvider().observe(
observeInput(fake.endpoint, fake.targetId, "node"),
);
if (!observed.ok) throw observed.error;
expect(observed.value.scripts.excluded).toMatchObject({
invalid_protocol_value: 1,
});
expect(observed.value.scripts.parse_failed_total).toBe(0);
} finally {
await fake.close();
}
});
const runtimeFixture = async () => {
const root = await createNodeDiscoveryTempDirectory("rea-v8-runtime-");
const entry = join(root, "entry.js");
await writeFile(entry, "export const value = 1;\n");
return { root, entry };
};
const temporaryFile = async (name: string): Promise<string> => {
const root = await createNodeDiscoveryTempDirectory("rea-v8-outside-");
const path = join(root, name);
await writeFile(path, "export {};\n");
return path;
};
const observeInput = (
endpoint: string,
targetId: string,
runtimeKind: ObserveJavaScriptRuntimeInput["runtime_kind"],
): ObserveJavaScriptRuntimeInput => ({
inspector_endpoint: endpoint,
target_id: targetId,
runtime_kind: runtimeKind,
observation_ms: 10,
});
const runtimeObservation = (
targetPath: string,
scriptPath: string,
): JavaScriptRuntimeObservation => ({
runtime: {
product: "node.js/v24.4.1",
protocol_version: "1.3",
v8_version: "13.6",
},
target: {
target_id: "example-v8-target",
protocol_type: "node",
attached: false,
location: { kind: "file", file_path: targetPath },
runtime_kind: "electron-main",
runtime_kind_authority: "caller-declared-unverified",
},
capture: {
observation_ms: 100,
events_observed: 1,
events_retained: 1,
events_dropped: 0,
metadata_bytes_retained: 100,
truncated: false,
truncation_reasons: [],
},
scripts: {
items: [
{
script_key: `v8_script_${"4".repeat(64)}`,
location: { kind: "file", file_path: scriptPath },
execution_context_key: "1",
execution_context_id: 1,
cdp_hash: "v8-hash",
length: 29,
is_module: true,
status: "observed-loaded",
},
],
observed_total: 1,
parse_failed_total: 0,
excluded: {
unsupported_location: 0,
invalid_protocol_value: 0,
},
},
execution_contexts: [],
directly_observed: ["Debugger.scriptParsed established script presence."],
unavailable_without_instrumentation: [
"require/import caller-to-callee edges",
],
unknowns: ["Capture is bounded."],
limitations: ["Passive Inspector metadata only."],
});