Files
reverse-engineering-anything/tests/boundary/cli/javascriptApplicationJsonOutput.test.ts
T
吴佳浩Albenand吴佳浩 afa34825a8 fix(javascript): drop a stream acquisition whose options Node refuses (#9262)
* fix(javascript): drop a stream acquisition whose options Node refuses

`fs.createReadStream` and `fs.createWriteStream` are tracked as acquisitions with
`close`/`destroy` releases, so a wrongly retained one also invents a teardown. Node
validates five option members before it constructs the stream, and the filter
inspected none of them. Measured on Node 24.22.1, seven shapes were wrong:

| call | Node | before |
| --- | --- | --- |
| `createReadStream(p, {start:-1})` | throws | retained |
| `createReadStream(p, {end:-5})` | throws | retained |
| `createReadStream(p, {start:10, end:2})` | throws | retained |
| `createWriteStream(p, {start:-1})` | throws | retained |
| `createReadStream(p, {fd:-1})` | throws | retained |
| `createReadStream(p, {highWaterMark:-1})` | throws | retained |
| `createReadStream(p, {encoding:5})` | throws | retained |

Each member has its own check, so each is decided separately:

- `start` / `end` need a non-negative integer number. A string, `null`, boolean or
  BigInt throws `ERR_INVALID_ARG_TYPE`; `undefined` is absent and `-0` is zero.
- `fd` applies the same number rule but treats `null` as absent.
- `highWaterMark` throws `ERR_INVALID_ARG_VALUE` below zero or for a fraction, and
  treats `null` as absent.
- `encoding` is skipped by Node when falsy, so only a truthy literal is decided and a
  string must be one `Buffer` accepts.
- `start` above `end` throws, so the pair is read together.
- `createWriteStream` has no `end` member at all, so `{end:-1}` still creates a handle.
- `flags`, `mode` and `autoClose` are not validated eagerly and stay undecided.

A decided rejection is only trusted while the constructor it dispatches through is
still Node's own. `Object.prototype`, the stream prototypes, the fs stream
constructors and their shared `Stream` / `EventEmitter` ancestors are all consulted
through `prototypeMutationMayPrecede`, `builtinModuleSlotUnmodified`,
`builtinModuleSubtreeUnmodified` and `builtinSharedPrototypeUnmodified`, so a
replaced constructor or an intercepting prototype keeps the acquisition and reports
`resolution: "partial"` instead of inventing a rejection.

This is a port of the branch onto current `main`. `javascriptSemanticMemberMutations`
was restructured into an `executions` dispatch while the branch sat, so the net change
is applied to one base with the conflict blocks resolved:

- The `Object.defineProperty` analysis moved into `markBuiltinPropertyDefinition`,
  called from the `case "call"/"construction"` branch, and `markInvocation` takes an
  optional `definedTarget` so a discarded result is still stepped over.
- `requiredModuleChanged` keeps main's `allowCandidate` / `ignoreCandidateEffects` /
  `snapshotObjectRoot` parameters and appends `descendantsMatter` /
  `ignoreRootSlotWrite`; the three guards spell every argument because the position
  of `allowCandidate` differs from the branch's.
- A namespace reached through a candidate loader is still the original built-in
  receiver, so the guards pass that allowance and `markBuiltinPropertyDefinition`
  accepts the same single-candidate origin `semanticExpressionModuleOrigin` does.
- `semanticEffectTiming` reads became `prototypeMutationMayPrecede` and
  `ambientPathMayObserveAt`, which the architecture guard requires.
- `isUnmodifiedGlobalReference` imports from `javascriptSemanticGlobalReference.js`;
  both `AmbientWrites` modules lack it.

49 new cases in `javascriptSemanticAnalysis.open_flag_literal.test.ts`, 29 of which
fail on the base commit. With the guards' arguments in the branch's order the file is
10 failed / 298 passed and every failure is a case that must still refuse; now 308
passing. `src/domain/javascript` + `src/application/javascript` — 7 009 passing.
`architecture-guards` passed across 2 818 files. `tsc --noEmit` 0 errors.
`npm run lint` 0 errors.

* fix(javascript): refuse BigInt and import.meta stream option members

* fix(javascript): evaluate a unary BigInt chain before deciding stream truthiness

* fix(javascript): keep an fd supplied through import.meta undecided

* refactor(javascript): route the acquisition coverage through the accumulator

---------

Co-authored-by: 吴佳浩 <wujiahao@supremind.com>
2026-11-26 10:42:33 -05:00

384 lines
12 KiB
TypeScript

import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { z } from "zod";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { analyzeJavaScriptApplication } from "../../support/javascriptApplicationScope.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
const filter = "evidence_id,normalized_result.graph.nodes[0,1].node_id";
cliTest(
"reports a replaced stream constructor as an uncertain resource",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-js-stream-constructor-");
await writeFile(
join(root, "main.js"),
`
const fs = require("node:fs");
Object.defineProperty(fs, "ReadStream", { value: Custom });
const stream = fs.createReadStream("input", { start: -1 });
stream.close();
`,
);
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode).toBe(0);
const data = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(output.json).normalized_result;
expect(data.semantic_graph.relations).toEqual(
expect.arrayContaining([
expect.objectContaining({
relation: "acquires",
resolution: "candidate",
}),
expect.objectContaining({
relation: "releases",
resolution: "candidate",
}),
]),
);
expect(data.semantic_graph.unknowns).toEqual(
expect.arrayContaining([
expect.objectContaining({
family: "resource-lifecycle",
relation_kinds: ["acquires"],
}),
]),
);
},
);
cliTest(
"retains stream resources after named constructor and validator mutations",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-js-stream-named-import-");
await writeFile(
join(root, "main.mjs"),
`
import fs, { ReadStream } from "node:fs";
import { Buffer as B } from "node:buffer";
Object.defineProperty(ReadStream.prototype, "start", { get() { return 0; }, set(value) {} });
B.isEncoding = () => true;
const reader = fs.createReadStream("input", { start: -1 });
reader.close();
const writer = fs.createWriteStream("output", { encoding: "nope" });
writer.close();
`,
);
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode).toBe(0);
const data = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(output.json).normalized_result;
expect(
data.semantic_graph.relations.filter(
({ relation }) => relation === "acquires",
),
).toHaveLength(2);
expect(
data.semantic_graph.relations.filter(
({ relation }) => relation === "releases",
),
).toHaveLength(2);
expect(data.semantic_graph.relations).toEqual(
expect.arrayContaining([
expect.objectContaining({
relation: "acquires",
resolution: "candidate",
}),
expect.objectContaining({
relation: "releases",
resolution: "candidate",
}),
]),
);
},
);
cliTest(
"retains stream resources after inherited prototype mutations and constructor escapes",
async ({ cli }) => {
const root = await createTestTempDirectory(
"rea-js-stream-shared-prototype-",
);
await writeFile(
join(root, "main.mjs"),
`
import fs, { ReadStream } from "node:fs";
import { Writable } from "node:stream";
import { Buffer as B } from "node:buffer";
configure(ReadStream); configure(B);
Object.defineProperty(Writable.prototype, "start", { get() { return 0; }, set(value) {} });
const reader = fs.createReadStream("input", { start: -1 }); reader.close();
const writer = fs.createWriteStream("output", { start: -1 }); writer.close();
`,
);
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode).toBe(0);
const graph = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(output.json).normalized_result.semantic_graph;
expect(
graph.relations.filter(({ relation }) => relation === "acquires"),
).toHaveLength(2);
expect(
graph.relations.filter(({ relation }) => relation === "releases"),
).toHaveLength(2);
},
);
for (const scenario of [
{
command: "analyze-javascript-application",
format: "json",
fullOutput: false,
filtered: true,
},
{
command: "analyze-javascript-application",
format: "jsonl",
fullOutput: true,
filtered: true,
},
{ command: "analyze", format: "json", fullOutput: true, filtered: false },
{ command: "analyze", format: "jsonl", fullOutput: false, filtered: false },
] as const) {
cliTest(
`${scenario.command} ${scenario.format === "jsonl" ? "refuses graph documents without a supported record boundary" : "preserves representative JSON output"}`,
async ({ cli }) => {
const root = await createTestTempDirectory("rea-js-json-output-");
await writeFile(join(root, "main.js"), "fetch('');\n");
const direct = await analyzeJavaScriptApplication({ input_path: root });
if (!direct.ok) throw direct.error;
const normalized = javascriptApplicationAnalysisResultSchema.parse(
direct.value.normalized_result,
);
const output = await cli.run({
arguments: [
scenario.command,
root,
"--format",
scenario.format,
...(scenario.fullOutput ? ["--full-output"] : []),
...(scenario.filtered ? ["--filter-output", filter] : []),
],
});
if (scenario.format === "jsonl") {
expect(output.exitCode).toBe(1);
const record = z
.object({
$rea: z.literal("jsonl/v1"),
type: z.literal("error"),
result: z.unknown(),
})
.parse(output.json);
const failure = scenario.fullOutput
? z
.object({
ok: z.literal(false),
error: z.unknown(),
meta: z.object({ command: z.literal(scenario.command) }),
})
.parse(record.result).error
: record.result;
expect(failure).toMatchObject({
code: "invalid_request",
category: "invalid_input",
remediation: {
action: expect.stringMatching(
/--format json.*record collection.*--filter-output/iu,
),
},
details: {
issues: [
{
path: [scenario.filtered ? "filter-output" : "format"],
reason: "invalid_value",
},
],
},
});
return;
}
expect(output.exitCode).toBe(0);
let data: unknown = output.json;
if (scenario.fullOutput) {
const envelope = z
.object({
ok: z.literal(true),
data: z.unknown(),
meta: z.object({
command: z.literal(scenario.command),
duration: z.string().regex(/^\d+ms$/u),
}),
})
.parse(output.json);
data = envelope.data;
}
expect(data).toEqual(
scenario.filtered
? {
evidence_id: direct.value.evidence_id,
normalized_result: {
graph: {
nodes: normalized.graph.nodes
.slice(0, 1)
.map(({ node_id }) => ({ node_id })),
},
},
}
: direct.value,
);
if (scenario.filtered)
expect(normalized.graph.nodes.length).toBeGreaterThan(0);
},
);
}
cliTest(
"preserves a complete empty filtered JSON document",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-js-json-empty-filter-");
await writeFile(join(root, "main.js"), "export const value = 1;\n");
const output = await cli.run({
arguments: [
"analyze-javascript-application",
root,
"--json",
"--filter-output",
"absent.field",
],
});
expect(output.exitCode).toBe(0);
expect(output.json).toEqual({});
},
);
cliTest(
"preserves a typed failed analysis in the JSON result",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-js-json-failure-");
const output = await cli.run({
arguments: [
"analyze-javascript-application",
join(root, "absent"),
"--json",
],
});
expect(output.json).toMatchObject({
code: "invalid_request",
details: { issues: [{ path: ["path"], reason: "invalid_value" }] },
});
},
);
cliTest(
"preserves JSON omission for inherited filter methods",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-js-json-inherited-filter-");
await writeFile(join(root, "main.js"), "export const value = 1;\n");
const output = await cli.run({
arguments: [
"analyze-javascript-application",
root,
"--json",
"--filter-output",
"toString",
],
});
expect(output.exitCode).toBe(0);
expect(output.json).toEqual({});
},
);
cliTest(
"honors caller-selected semantic node limits across files and records them in Evidence",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-js-node-budgets-");
await writeFile(join(root, "first.js"), "external;\n".repeat(40));
await writeFile(join(root, "second.js"), "another;\n".repeat(40));
const output = await cli.run({
arguments: [
"analyze-javascript-application",
root,
"--format",
"json",
"--max-semantic-nodes",
"50",
"--max-semantic-nodes-per-file",
"30",
],
});
expect(output.exitCode).toBe(0);
const result = z
.object({
parameters: z.object({
max_semantic_nodes: z.number(),
max_semantic_nodes_per_file: z.number(),
}),
normalized_result: z.object({
semantic_graph: z.object({
nodes: z.array(
z.object({ identity: z.object({ module_path: z.string() }) }),
),
coverage: z.object({
truncated: z.boolean(),
omitted_nodes: z.number().nullable(),
limits: z.array(
z.object({ name: z.string(), value: z.number() }),
),
}),
}),
}),
})
.parse(output.json);
expect(result.parameters).toEqual({
max_semantic_nodes: 50,
max_semantic_nodes_per_file: 30,
});
const graph = result.normalized_result.semantic_graph;
expect(graph.nodes).toHaveLength(50);
expect(
graph.nodes.filter((node) => node.identity.module_path === "first.js"),
).toHaveLength(30);
expect(
graph.nodes.filter((node) => node.identity.module_path === "second.js"),
).toHaveLength(20);
expect(graph.coverage.truncated).toBe(true);
expect(graph.coverage.omitted_nodes).toBeNull();
expect(graph.coverage.limits).toEqual(
expect.arrayContaining([
{ name: "semantic_graph_node_ceiling", value: 50 },
{ name: "semantic_graph_file_node_ceiling", value: 30 },
{ name: "max_semantic_nodes", value: 50 },
{ name: "max_semantic_nodes_per_file", value: 30 },
]),
);
const limitation = z
.object({
normalized_result: z.object({
semantic_graph: z.object({
limitations: z.array(z.string()),
}),
}),
})
.parse(output.json);
expect(
limitation.normalized_result.semantic_graph.limitations.join("\n"),
).toContain("max_semantic_nodes");
expect(
limitation.normalized_result.semantic_graph.limitations.join("\n"),
).toContain("1 to 1000000");
},
);