Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(javascript): retain directive values in function fingerprints

morluto639685195824
diff --git a/docs/javascript-application-workflows.md b/docs/javascript-application-workflows.md
index e9fed813f..9c5475737 100644
--- a/docs/javascript-application-workflows.md
+++ b/docs/javascript-application-workflows.md
@@ -86,7 +86,14 @@ outside this mutation pass.
Function fingerprints commit normalized syntax, control-flow shape, relation
shape, literal sets, arity, and detected effects without using local names or
-source offsets. Equal duplicate fingerprints remain ambiguous. Dynamic
+source offsets. Function-local directive literals contribute their values while
+preserving escape spelling: `"use\x20strict"` differs from `"use strict"`.
+Quote style, formatting, and local names remain normalized. Equal duplicate
+fingerprints remain ambiguous.
+Fingerprints are static candidates, not behavioral-equivalence proofs or a
+version-independent identity. Re-analyze affected sources and obtain new seeds
+after analyzer corrections; previously retained Evidence remains queryable using
+its original component commitments. Dynamic
calls/properties/names, parser recovery, unresolved handles, and unsupported API
shapes stay explicit unknowns; a missing relation is never reported as proven
behavioral absence.
diff --git a/src/domain/javascript/javascriptSemanticAnalysis.fingerprints.test.ts b/src/domain/javascript/javascriptSemanticAnalysis.fingerprints.test.ts
new file mode 100644
index 000000000..ce88236a5
--- /dev/null
+++ b/src/domain/javascript/javascriptSemanticAnalysis.fingerprints.test.ts
@@ -0,0 +1,65 @@
+import { expect, it } from "vitest";
+
+import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
+
+const components = (source: string) => {
+ const ir = analyzeJavaScriptSemantics(source);
+ expect(ir.functionFingerprints).toHaveLength(1);
+ const fingerprint = ir.functionFingerprints[0];
+ if (fingerprint === undefined)
+ throw new Error("Expected a function fingerprint");
+ expect(fingerprint.status).toBe("complete");
+ return fingerprint.components;
+};
+
+it.each([
+ ["recognized directives", '"use strict"', '"use asm"'],
+ ["ordinary directives", '"alpha"', '"beta"'],
+ ["empty directive", '""', '"alpha"'],
+ ["escaped strict spelling", '"use strict"', String.raw`"use\x20strict"`],
+])("retains %s in the function literal commitment", (_name, left, right) => {
+ const source = (directive: string) =>
+ `function sample(value) { ${directive}; return value; }`;
+ expect(components(source(left)).literalSetSha256).not.toBe(
+ components(source(right)).literalSetSha256,
+ );
+});
+
+it.each([
+ [
+ 'function sample(value) { "use strict"; return value; }',
+ "function renamed(input) {\n 'use strict' ;\n return input;\n}",
+ ],
+ [
+ String.raw`function sample(value) { "use\x20strict"; return value; }`,
+ String.raw`function renamed(input) { 'use\x20strict'; return input; }`,
+ ],
+])(
+ "normalizes quote style, formatting and names for %s",
+ (original, renamed) => {
+ expect(components(renamed)).toEqual(components(original));
+ },
+);
+
+it("keeps a nested function's directive out of its owner fingerprint", () => {
+ const analyze = (directive: string) => {
+ const ir = analyzeJavaScriptSemantics(
+ `function outer() { function inner(value) { ${directive}; return value; } return 1; }`,
+ );
+ return new Map(
+ ir.functionFingerprints.map((fingerprint) => [
+ ir.callables.find(
+ ({ callableId }) => callableId === fingerprint.callableId,
+ )?.name,
+ fingerprint.components,
+ ]),
+ );
+ };
+ const first = analyze('"use strict"');
+ const second = analyze('"ordinary"');
+ expect(first.size).toBe(2);
+ expect(second.get("outer")).toEqual(first.get("outer"));
+ expect(second.get("inner")?.literalSetSha256).not.toBe(
+ first.get("inner")?.literalSetSha256,
+ );
+});
diff --git a/src/domain/javascript/javascriptSemanticFingerprints.ts b/src/domain/javascript/javascriptSemanticFingerprints.ts
index 6212ee5e4..d46305362 100644
--- a/src/domain/javascript/javascriptSemanticFingerprints.ts
+++ b/src/domain/javascript/javascriptSemanticFingerprints.ts
@@ -252,6 +252,9 @@ const controlFlowToken = (node: t.Node): string | null => {
};
const semanticLiteral = (node: t.Node): string | null => {
+ // Babel retains directive escapes in value; decoding them would erase the
+ // distinction between a strict-mode directive and an escaped lookalike.
+ if (t.isDirectiveLiteral(node)) return `directive:${node.value}`;
if (t.isStringLiteral(node)) return `string:${node.value}`;
if (t.isNumericLiteral(node)) return `number:${String(node.value)}`;
if (t.isBooleanLiteral(node)) return `boolean:${String(node.value)}`;
diff --git a/tests/acceptance/applications/javascriptFunctionFingerprintsCli.test.ts b/tests/acceptance/applications/javascriptFunctionFingerprintsCli.test.ts
new file mode 100644
index 000000000..f66c08366
--- /dev/null
+++ b/tests/acceptance/applications/javascriptFunctionFingerprintsCli.test.ts
@@ -0,0 +1,127 @@
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { expect } from "vitest";
+
+import { toolContract } from "../../../src/contracts/toolContracts.js";
+import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
+import { javaScriptSemanticTraceResultSchema } from "../../../src/domain/javascript/javascriptSemanticTraceSchemas.js";
+import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import { cliTest } from "../../support/cli/cliFixture.js";
+
+cliTest(
+ "function fingerprint seeds retain directive values and normalized duplicates through CLI and MCP",
+ async ({ cli }) => {
+ const root = await createTestTempDirectory("rea-function-fingerprints-");
+ const application = join(root, "application");
+ await mkdir(application);
+ await writeFile(
+ join(application, "app.cjs"),
+ String.raw`
+ throw new Error("This analysis fixture must not execute");
+ function strict(value) { "use strict"; return value; }
+ function ordinary(value) { "ordinary"; return value; }
+ function asm(value) { "use asm"; return value; }
+ function alpha(value) { "alpha"; return value; }
+ function beta(value) { "beta"; return value; }
+ function escaped(value) { "use\x20strict"; return value; }
+ function renamed(input) { 'use strict'; return input; }
+ `,
+ );
+ const analyzed = await cli.run({
+ arguments: [
+ "analyze-javascript-application",
+ application,
+ "--artifact-format",
+ "directory",
+ "--json",
+ ],
+ environment: { REA_LOG_LEVEL: "silent" },
+ });
+ expect(analyzed.exitCode, analyzed.stderr).toBe(0);
+ const evidence = toolContract(
+ "analyze_javascript_application",
+ ).outputSchema.parse(analyzed.json);
+ const { semantic_graph: graph } =
+ javascriptApplicationAnalysisResultSchema.parse(
+ evidence.normalized_result,
+ );
+ const { client, call } = await connectLocalToolsMcp();
+ const response = await call("analyze_javascript_application", {
+ input_path: application,
+ format: "directory",
+ });
+ expect(response.isError).not.toBe(true);
+ const retained = toolContract(
+ "analyze_javascript_application",
+ ).outputSchema.parse(response.structuredContent);
+ expect(retained.evidence_id).toBe(evidence.evidence_id);
+ const fingerprint = (name: string) => {
+ const node = graph.nodes.find(
+ (candidate) =>
+ candidate.kind === "function" && candidate.properties.name === name,
+ );
+ if (node === undefined) throw new Error(`Missing function ${name}`);
+ const result = graph.fingerprints.find(
+ ({ function_node_id }) => function_node_id === node.node_id,
+ );
+ if (result === undefined) throw new Error(`Missing fingerprint ${name}`);
+ expect(result.status).toBe("complete");
+ return result;
+ };
+ for (const [selected, expectedNames] of [
+ ["strict", ["strict", "renamed"]],
+ ["ordinary", ["ordinary"]],
+ ["asm", ["asm"]],
+ ["alpha", ["alpha"]],
+ ["beta", ["beta"]],
+ ["escaped", ["escaped"]],
+ ] as const) {
+ const query = {
+ seed: {
+ kind: "function",
+ fingerprint_sha256: fingerprint(selected).fingerprint_sha256,
+ },
+ direction: "forward-influence",
+ };
+ const traced = await call("trace_javascript_semantics", {
+ application: {
+ kind: "retained-evidence",
+ evidence_id: retained.evidence_id,
+ },
+ query,
+ });
+ expect(traced.isError, JSON.stringify(traced)).not.toBe(true);
+ const traceEvidence = toolContract(
+ "trace_javascript_semantics",
+ ).outputSchema.parse(traced.structuredContent);
+ const trace = javaScriptSemanticTraceResultSchema.parse(
+ traceEvidence.normalized_result,
+ );
+ expect(trace.seed_node_ids).toEqual(
+ expectedNames.map((name) => fingerprint(name).function_node_id).sort(),
+ );
+ expect(trace.status).toBe(
+ expectedNames.length > 1 ? "ambiguous" : "found",
+ );
+ expect(trace.source_graph_id).toBe(graph.graph_id);
+ if (selected === "strict") {
+ const requestPath = join(root, "trace-request.json");
+ await writeFile(
+ requestPath,
+ JSON.stringify({ application: evidence, query }),
+ );
+ const cliTrace = await cli.run({
+ arguments: ["trace-javascript-semantics", requestPath, "--json"],
+ environment: { REA_LOG_LEVEL: "silent" },
+ });
+ expect(cliTrace.exitCode, cliTrace.stderr).toBe(0);
+ const cliEvidence = toolContract(
+ "trace_javascript_semantics",
+ ).outputSchema.parse(cliTrace.json);
+ expect(cliEvidence.evidence_id).toBe(traceEvidence.evidence_id);
+ }
+ }
+ await client.ping();
+ },
+);