Files
reverse-engineering-anything/src/domain/javascript/javascriptElectronMemberWrites.ts
T
Yann Robertoandbaron 653067d799 fix(javascript): resolve module-relative Worker URL references (#2104)
* fix(javascript): resolve module-relative Worker URL references

* fix(javascript): validate Worker URL paths independently of suffixes

* fix(javascript): preserve directory-form Worker URL paths

* fix(javascript): unwrap type assertions in Worker URL references

* fix(javascript): validate Worker bindings before URL resolution

* fix(javascript): leave drive-letter Worker URLs unresolved

Use WHATWG file URL parsing before pathname decoding to detect drive-letter
forms whose resource identity depends on the unmodeled source URL scheme.
Preserve encoded and ordinary relative pipe paths, and cover false matches
through the compiled CLI and resolver boundary tests.

* fix(javascript): preserve Worker URL identity boundaries

Recognize known Worker bindings before filtering callee spellings so ESM
aliases and transparent constructor wrappers reach URL analysis. Keep
root-relative module URLs unknown without a modeled runtime base root.

Index direct source-local global writes with the shared mutation collector
before promoting URL and browser Worker constructors. Preserve lexical
shadowing and unrelated property identities, and exercise all three review
regressions through the compiled CLI.

* fix(javascript): invalidate mutated import.meta URL bases

Track source-local import.meta writes alongside ambient global writes so
Worker URL expressions keep an unknown base after a possible URL mutation.
Tag the identity roots independently and cover direct mutation and unrelated
property cases through the compiled CLI.

* fix(javascript): close Worker URL identity and pathname gaps

Resolve ambient object identities before appending written properties, and
retain possible source-local aliases across rebinding. Reuse intrinsic
invocation handling for aliased and bound mutators, array spreads, and
transparent TypeScript wrappers while preserving Electron write semantics.

Keep malformed-percent nested Worker URL pathnames unknown because the base
scheme is unavailable and Node rejects these file URLs. Preserve tolerant
HTML URL handling, valid escapes, and query/fragment evidence.

Cover the new cases and unrelated writes through the compiled CLI with
existing-file decoys. All 591 targeted tests and npm run check pass.

* fix(javascript): bound alias expansion and classify Worker paths

Join ambient identity projections instead of enumerating alias histories.
Memoize repeated value and provenance queries while preserving capture,
depth, and cycle-dependent uncertainty.

Keep Node Worker string arguments unresolved without filesystem or cwd
context, and admit qualified global URL constructors through identity checks.

Validate three 40-level alias branch shapes through the compiled CLI,
925 source tests, 25 CLI/boundary tests, and the full npm run check gate.

* fix(server): preserve partial Evidence target-content provenance

Pass the exact named contract returnsTargetContent flag through the shared partial-Evidence error delivery path introduced by the shortlist integration.

Exercise successful and failed recording through in-memory MCP for marked and unmarked contracts, preserving source payload and original failures. Observe both shared-handler emission and wire delivery so the SDK error-marker fallback cannot hide omissions. Suppressing the flag fails exactly the two marked cases.

Validation: check:fast, check, 736 semantic tests, 29 MCP transport/error tests and six compiled static Worker CLI journeys pass. No live target/provider execution or hosted publication.

* fix(javascript): structurally share semantic dependency proofs

---------

Co-authored-by: baron <richstyles@gmail.com>
2026-10-13 07:24:45 +09:00

168 lines
6.5 KiB
TypeScript

import * as t from "@babel/types";
import {
semanticStaticPropertyKey,
semanticWriteTargets,
unwrapJavaScriptExpression,
} from "./javascriptAstValues.js";
import { traverseJavaScriptAstSteps } from "./javascriptSemanticTraversal.js";
/** Match Electron's supported module entry points. */
export const ELECTRON_MODULE =
/^electron(?:\/(?:common|main|renderer|utility))?$/u;
/**
* Electron's CommonJS exports define no `default` member, so a leading
* `default` segment can only denote the module object itself, as an ES module
* default import (`import electron from "electron"`) binds it.
*/
export const electronExportPath = (
importedPath: readonly string[],
): readonly string[] =>
importedPath[0] === "default" ? importedPath.slice(1) : importedPath;
/** Static identity recovery cannot establish the absence of Electron usage. */
export const ELECTRON_IDENTITY_LIMITATION =
"Electron API identity follows proven lexical module aliases and structurally verified module-namespace interop. Other reassignments, dynamic selections, and visibly overwritten namespace members are unresolved; missing findings do not establish absence. Arbitrary call side effects and runtime registration are not evaluated.";
/** Preserve exact property segments instead of flattening literal dotted keys. */
export const electronMemberPath = (
node: t.Node,
): {
readonly root: t.Node;
readonly members: readonly (string | null)[];
} => {
let root = unwrapJavaScriptExpression(node).node;
const members: (string | null)[] = [];
while (t.isMemberExpression(root) || t.isOptionalMemberExpression(root)) {
members.push(semanticStaticPropertyKey(root.property, root.computed));
root = unwrapJavaScriptExpression(root.object).node;
}
return { root, members: members.toReversed() };
};
/** A known intrinsic callable and its examined positional arguments. */
export interface JavaScriptIntrinsicInvocation {
readonly kind: "known" | "opaque";
/** The original bound receiver; rebinding cannot replace it. */
readonly receiver?: t.Node;
readonly path: readonly string[];
readonly arguments:
| readonly t.CallExpression["arguments"][number][]
| undefined;
}
/**
* Index writes through possible lexical object identities. Resolve the complete
* object before appending the written key: self-reference properties can denote
* the same object, while replacing that property is a distinct write.
*/
export function* collectJavaScriptIdentityWritesSteps(
program: t.Program,
origin: (
root: t.Node,
kind: "binding" | "member" | "opaque-call",
) => readonly (readonly (string | null)[])[],
intrinsicInvocation: (
node: t.CallExpression | t.OptionalCallExpression,
) => JavaScriptIntrinsicInvocation | undefined,
staticString: (node: t.Node | undefined) => string | undefined,
freshObject: (node: t.Node) => boolean,
retain: (node: t.Node, path: readonly (string | null)[]) => void,
): Generator<void> {
const objectMutators = new Set([
"defineProperty",
"defineProperties",
"assign",
"setPrototypeOf",
]);
const reflectMutators = new Set([
"set",
"deleteProperty",
"defineProperty",
"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") {
for (const scope of origin(node, "opaque-call")) 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)) {
for (const scope of origin(node, "opaque-call"))
retain(node, scope);
}
if (t.isNode(target) && !t.isSpreadElement(target)) {
const identities = origin(target, "member");
if (identities.length > 0) {
const key = keyedMutators.has(method ?? "")
? [staticString(arguments_?.[1]) ?? null]
: [];
for (const identity of identities)
retain(node, [...identity, ...key]);
} else if (!freshObject(target)) {
for (const scope of origin(node, "opaque-call"))
retain(node, scope);
}
}
}
}
}
const target = t.isAssignmentExpression(node)
? node.left
: t.isUpdateExpression(node)
? node.argument
: t.isUnaryExpression(node, { operator: "delete" })
? node.argument
: t.isForOfStatement(node) || t.isForInStatement(node)
? node.left
: undefined;
if (target === undefined) return;
for (const leaf of semanticWriteTargets(target)) {
if (t.isIdentifier(leaf)) {
for (const identity of origin(leaf, "binding"))
retain(node, identity);
continue;
}
const member = unwrapJavaScriptExpression(leaf).node;
if (
!t.isMemberExpression(member) &&
!t.isOptionalMemberExpression(member)
)
continue;
const key = semanticStaticPropertyKey(member.property, member.computed);
for (const identity of origin(member.object, "member"))
retain(node, [...identity, key]);
}
},
});
}