fix(javascript): integrate verified namespace interop with main
Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
commit
9788112548
@@ -14,6 +14,7 @@ import {
|
||||
type ArtifactEntry,
|
||||
type ArtifactReader,
|
||||
} from "./ArtifactReader.js";
|
||||
import { hostExecutableMarking } from "./hostExecutableMarking.js";
|
||||
import { OwnedDirectoryHandle } from "../filesystem/OwnedDirectoryHandle.js";
|
||||
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
|
||||
import { readFileHandleChunks } from "../filesystem/readFileHandleChunks.js";
|
||||
@@ -270,7 +271,7 @@ const artifactEntry = (
|
||||
kind,
|
||||
declaredSize: kind === "file" ? metadata.size : null,
|
||||
compressedSize: null,
|
||||
executable: (metadata.mode & 0o111) !== 0,
|
||||
executable: hostExecutableMarking(absolute, metadata),
|
||||
encrypted: false,
|
||||
byteOffset: null,
|
||||
declaredSha256: null,
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { hostExecutableMarking } from "./hostExecutableMarking.js";
|
||||
|
||||
const file = (mode: number) => ({ mode, isFile: () => true });
|
||||
const directory = (mode: number) => ({ mode, isFile: () => false });
|
||||
|
||||
describe("hostExecutableMarking", () => {
|
||||
it("marks Windows launchable files by extension because NTFS has no execute bit", () => {
|
||||
expect(
|
||||
hostExecutableMarking("C:\\scratch\\whoami.exe", file(0o666), "win32"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
hostExecutableMarking("C:\\scratch\\SETUP.CMD", file(0o444), "win32"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
hostExecutableMarking("C:\\scratch\\library.dll", file(0o666), "win32"),
|
||||
).toBe(false);
|
||||
expect(
|
||||
hostExecutableMarking(
|
||||
"C:\\scratch\\tools.exe",
|
||||
directory(0o666),
|
||||
"win32",
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps POSIX permission bits authoritative regardless of extension", () => {
|
||||
expect(hostExecutableMarking("/scratch/tool", file(0o755), "linux")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
hostExecutableMarking("/scratch/whoami.exe", file(0o644), "darwin"),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { Stats } from "node:fs";
|
||||
import { extname } from "node:path";
|
||||
|
||||
/** Extensions Windows launches directly through CreateProcess or cmd.exe. */
|
||||
const windowsLaunchableExtensions = new Set([".bat", ".cmd", ".com", ".exe"]);
|
||||
|
||||
/**
|
||||
* Whether a host filesystem entry carries the host's executable marking.
|
||||
*
|
||||
* POSIX hosts mark executability with permission bits. Windows has no execute
|
||||
* bit (Node reports file modes from the read-only attribute alone), so it marks
|
||||
* launchable files by extension instead.
|
||||
*/
|
||||
export const hostExecutableMarking = (
|
||||
path: string,
|
||||
metadata: Pick<Stats, "mode" | "isFile">,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): boolean =>
|
||||
platform === "win32"
|
||||
? metadata.isFile() &&
|
||||
windowsLaunchableExtensions.has(extname(path).toLowerCase())
|
||||
: (metadata.mode & 0o111) !== 0;
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
artifactManifestId,
|
||||
} from "../../domain/artifactIdentity.js";
|
||||
import { classifyAndHashRootForInventory } from "./classify.js";
|
||||
import { hostExecutableMarking } from "../hostExecutableMarking.js";
|
||||
import type { HashResult } from "../ArtifactHash.js";
|
||||
import {
|
||||
hashStableRootArtifact,
|
||||
@@ -211,7 +212,7 @@ const buildInventorySnapshot = async (
|
||||
rekeyOccurrences(rootNode.artifact_id, input.occurrences);
|
||||
const rootOccurrence = rootOccurrenceFor(rootNode, {
|
||||
size: metadata.size,
|
||||
executable: (metadata.mode & 0o111) !== 0,
|
||||
executable: hostExecutableMarking(path, metadata),
|
||||
format: rootFormat,
|
||||
path,
|
||||
});
|
||||
|
||||
@@ -168,6 +168,32 @@ describe("Electron module interop uncertainty", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Electron module interop helper results", () => {
|
||||
it.each([
|
||||
"const __toESM = () => ({BrowserWindow:FakeWindow});",
|
||||
"const __toESM = async (mod) => mod;",
|
||||
"function* __toESM(mod) { return mod; }",
|
||||
"const __toESM = (this && this.__toESM) || ((mod) => mod);",
|
||||
])("keeps an unproven fresh result unresolved: %s", (helper) => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`${helper}
|
||||
const electron = __toESM(require("electron"), 1); ${WINDOW}
|
||||
new (__toESM(require("electron"), 1)).BrowserWindow({});
|
||||
`);
|
||||
expect(analysis.electron.browser_windows).toEqual([]);
|
||||
});
|
||||
|
||||
it("preserves a proven fresh namespace and a pure identity helper", () => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`${ROLLDOWN_MODULE_INTEROP}
|
||||
const electron = __toESM(require("electron"), 1); ${WINDOW}
|
||||
new (__toESM(require("electron"), 1)).BrowserWindow({});
|
||||
function passthrough(value) {return value;}
|
||||
const plain = passthrough(require("electron"));
|
||||
new plain.BrowserWindow({});
|
||||
`);
|
||||
expect(analysis.electron.browser_windows).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Electron module interop capture and scope", () => {
|
||||
it("does not reject unrelated intrinsic property definitions", () => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`
|
||||
|
||||
@@ -73,4 +73,51 @@ describe("Electron API identity", () => {
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("follows bundler namespace interop helpers without accepting other writes", () => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`
|
||||
var __toESM = (mod) => mod;
|
||||
var __importStar = (mod) => mod;
|
||||
let electron = require("electron");
|
||||
electron = __toESM(electron);
|
||||
new electron.BrowserWindow({ webPreferences: { preload: "./rolldown.js" } });
|
||||
var import_electron = __toESM(require("electron"));
|
||||
new import_electron.BrowserWindow({ webPreferences: { preload: "./esbuild.js" } });
|
||||
function _interopRequireWildcard(mod) { return mod; }
|
||||
const Electron = __importStar(require("electron"));
|
||||
new Electron.BrowserWindow({ webPreferences: { preload: "./tsc.js" } });
|
||||
|
||||
let replaced = require("electron");
|
||||
replaced = __toESM(require("./fake"));
|
||||
new replaced.BrowserWindow({ webPreferences: { preload: "./replaced.js" } });
|
||||
let rewritten = require("electron");
|
||||
rewritten = __toESM(rewritten);
|
||||
rewritten = fake;
|
||||
new rewritten.BrowserWindow({ webPreferences: { preload: "./rewritten.js" } });
|
||||
const babel = _interopRequireWildcard(require("electron"));
|
||||
new babel.BrowserWindow({ webPreferences: { preload: "./babel.js" } });
|
||||
function nested() {
|
||||
const __toESM = (mod) => mod;
|
||||
const scoped = __toESM(require("electron"));
|
||||
new scoped.BrowserWindow({ webPreferences: { preload: "./nested.js" } });
|
||||
}
|
||||
`);
|
||||
|
||||
expect(
|
||||
analysis.electron.browser_windows.map(({ preload_path }) => preload_path),
|
||||
).toEqual(["./rolldown.js", "./esbuild.js", "./tsc.js", "./babel.js"]);
|
||||
});
|
||||
|
||||
it("does not trust unbound helper names or non-function helper values", () => {
|
||||
const analysis = analyzeJavaScriptStaticSource(`
|
||||
const __toESM = makeLookalike();
|
||||
const electron = __toESM(require("electron"));
|
||||
new electron.BrowserWindow({});
|
||||
let unbound = require("electron");
|
||||
unbound = __importStar(unbound);
|
||||
new unbound.BrowserWindow({});
|
||||
`);
|
||||
|
||||
expect(analysis.electron.browser_windows).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -55,6 +55,7 @@ interface InteropOrigin {
|
||||
interface InteropHelper {
|
||||
readonly dependencies: readonly IntrinsicDependency[];
|
||||
readonly readyAfter: number;
|
||||
readonly identity: boolean;
|
||||
}
|
||||
|
||||
/** Prove one inert namespace conversion without relaxing general assignment semantics. */
|
||||
@@ -63,6 +64,7 @@ export const createSemanticModuleInterop = (
|
||||
) => {
|
||||
const helpers = new Map<string, InteropHelper | null>();
|
||||
const origins = new Map<string, InteropOrigin>();
|
||||
const calls = new WeakMap<t.Node, InteropOrigin>();
|
||||
const intrinsicBindings = new Map<string, readonly string[] | null>();
|
||||
const writes: {
|
||||
readonly scope: string;
|
||||
@@ -70,6 +72,7 @@ export const createSemanticModuleInterop = (
|
||||
readonly coverage: SemanticPropertyPathCoverage;
|
||||
}[] = [];
|
||||
const invalidatedBindings = new Map<string, boolean>();
|
||||
const invalidatedCalls = new WeakMap<t.Node, boolean>();
|
||||
const opaqueMutationPath = (node: t.Node): readonly string[] => {
|
||||
let current: t.Node | undefined = node;
|
||||
while (current !== undefined) {
|
||||
@@ -134,8 +137,21 @@ export const createSemanticModuleInterop = (
|
||||
const cached = helpers.get(binding.bindingId);
|
||||
if (cached !== undefined) return cached ?? undefined;
|
||||
helpers.set(binding.bindingId, null);
|
||||
if (state.scopesById.get(binding.scopeId)?.kind !== "program")
|
||||
return undefined;
|
||||
const wrapper = stableInitializer(binding, state);
|
||||
if (wrapper === undefined) return undefined;
|
||||
if (identityFunction(wrapper, state)) {
|
||||
const proof = {
|
||||
dependencies: [],
|
||||
readyAfter: t.isFunctionDeclaration(wrapper)
|
||||
? -1
|
||||
: (wrapper.end ?? Infinity),
|
||||
identity: true,
|
||||
};
|
||||
helpers.set(binding.bindingId, proof);
|
||||
return proof;
|
||||
}
|
||||
const wrapperRoles = canonicalRoles(wrapper, TO_ESM, state);
|
||||
const copyBinding = wrapperRoles?.get("__copyProps");
|
||||
const copy = stableInitializer(copyBinding, state);
|
||||
@@ -171,6 +187,7 @@ export const createSemanticModuleInterop = (
|
||||
);
|
||||
const proof = {
|
||||
dependencies,
|
||||
identity: false,
|
||||
readyAfter: Math.max(
|
||||
wrapper.end ?? Infinity,
|
||||
copy.end ?? Infinity,
|
||||
@@ -181,9 +198,62 @@ export const createSemanticModuleInterop = (
|
||||
return proof;
|
||||
};
|
||||
|
||||
const provenCall = (node: t.Node) => {
|
||||
if (!t.isCallExpression(node) || !t.isIdentifier(node.callee))
|
||||
return undefined;
|
||||
const helper = resolveSemanticBindingState(
|
||||
state,
|
||||
node.callee,
|
||||
node.callee.name,
|
||||
);
|
||||
const proof = helper === undefined ? undefined : helperProof(helper);
|
||||
const input = node.arguments[0];
|
||||
if (
|
||||
proof === undefined ||
|
||||
proof.readyAfter >= (node.start ?? -1) ||
|
||||
!t.isExpression(input) ||
|
||||
(!proof.identity &&
|
||||
(node.arguments.length !== 2 ||
|
||||
!t.isNumericLiteral(node.arguments[1], { value: 1 })))
|
||||
)
|
||||
return undefined;
|
||||
return {
|
||||
input,
|
||||
dependencies: proof.dependencies.map((dependency) => ({
|
||||
...dependency,
|
||||
capturedAt: dependency.capturedAt ?? node,
|
||||
})),
|
||||
};
|
||||
};
|
||||
|
||||
const callOrigin = (node: t.Node): InteropOrigin | undefined => {
|
||||
const cached = calls.get(node);
|
||||
if (cached !== undefined) return cached;
|
||||
const converted = provenCall(node);
|
||||
const required =
|
||||
converted === undefined
|
||||
? undefined
|
||||
: semanticRequireOrigin(converted.input, state)?.origin;
|
||||
if (
|
||||
converted === undefined ||
|
||||
required === undefined ||
|
||||
required.importedPath.length !== 0
|
||||
)
|
||||
return undefined;
|
||||
const result = { origin: required, dependencies: converted.dependencies };
|
||||
calls.set(node, result);
|
||||
return result;
|
||||
};
|
||||
|
||||
const origin = (
|
||||
binding: JavaScriptSemanticBindingState,
|
||||
): InteropOrigin | undefined => {
|
||||
const single = stableInitializer(binding, state);
|
||||
if (single !== undefined) {
|
||||
const result = callOrigin(single);
|
||||
if (result !== undefined) origins.set(binding.bindingId, result);
|
||||
return result;
|
||||
}
|
||||
const [initial, converted] = binding.initializers;
|
||||
if (
|
||||
binding.definitions.length !== 2 ||
|
||||
@@ -219,12 +289,11 @@ export const createSemanticModuleInterop = (
|
||||
!t.isVariableDeclaration(declarationStatement) ||
|
||||
state.parentsByNode.get(statement) !==
|
||||
state.parentsByNode.get(declarationStatement) ||
|
||||
(initial.node.start ?? Infinity) >= (call.start ?? -1) ||
|
||||
call.arguments.length !== 2 ||
|
||||
!t.isNumericLiteral(call.arguments[1], { value: 1 })
|
||||
(initial.node.start ?? Infinity) >= (call.start ?? -1)
|
||||
)
|
||||
return undefined;
|
||||
const input = call.arguments[0];
|
||||
const convertedCall = provenCall(call);
|
||||
const input = convertedCall?.input;
|
||||
if (
|
||||
!t.isIdentifier(input) ||
|
||||
resolveSemanticBindingState(state, input, input.name) !== binding
|
||||
@@ -233,26 +302,30 @@ export const createSemanticModuleInterop = (
|
||||
const required = semanticRequireOrigin(initial.node, state)?.origin;
|
||||
if (required === undefined || required.importedPath.length !== 0)
|
||||
return undefined;
|
||||
const helper = resolveSemanticBindingState(
|
||||
state,
|
||||
call.callee,
|
||||
call.callee.name,
|
||||
);
|
||||
const proof = helper === undefined ? undefined : helperProof(helper);
|
||||
if (proof === undefined || proof.readyAfter >= (call.start ?? -1))
|
||||
return undefined;
|
||||
if (convertedCall === undefined) return undefined;
|
||||
const result = {
|
||||
origin: required,
|
||||
dependencies: proof.dependencies.map((dependency) => ({
|
||||
...dependency,
|
||||
capturedAt: dependency.capturedAt ?? call,
|
||||
})),
|
||||
dependencies: convertedCall.dependencies,
|
||||
};
|
||||
origins.set(binding.bindingId, result);
|
||||
return result;
|
||||
};
|
||||
const invalidatedOrigin = (record: InteropOrigin | undefined): boolean =>
|
||||
record?.dependencies.some(({ path, capturedAt }) => {
|
||||
if (capturedAt === undefined) return true;
|
||||
const scope = opaqueMutationPath(capturedAt).join(".");
|
||||
// Captured function values survive later replacement of global
|
||||
// properties. Other callable bodies are not execution evidence.
|
||||
return writes.some(
|
||||
(write) =>
|
||||
(write.scope === scope || write.scope === "intrinsic") &&
|
||||
write.offset < (capturedAt.start ?? -1) &&
|
||||
write.coverage.covers(path),
|
||||
);
|
||||
}) ?? false;
|
||||
return {
|
||||
origin,
|
||||
callOrigin,
|
||||
intrinsicPath,
|
||||
opaqueMutationPath,
|
||||
retainWrite: (node: t.Node, path: readonly (string | null)[]) => {
|
||||
@@ -267,27 +340,47 @@ export const createSemanticModuleInterop = (
|
||||
invalidated: (binding: JavaScriptSemanticBindingState): boolean => {
|
||||
const cached = invalidatedBindings.get(binding.bindingId);
|
||||
if (cached !== undefined) return cached;
|
||||
const result =
|
||||
origins
|
||||
.get(binding.bindingId)
|
||||
?.dependencies.some(({ path, capturedAt }) => {
|
||||
if (capturedAt === undefined) return true;
|
||||
const scope = opaqueMutationPath(capturedAt).join(".");
|
||||
// Captured function values survive later replacement of global
|
||||
// properties. Other callable bodies are not execution evidence.
|
||||
return writes.some(
|
||||
(write) =>
|
||||
(write.scope === scope || write.scope === "intrinsic") &&
|
||||
write.offset < (capturedAt.start ?? -1) &&
|
||||
write.coverage.covers(path),
|
||||
);
|
||||
}) ?? false;
|
||||
const result = invalidatedOrigin(origins.get(binding.bindingId));
|
||||
invalidatedBindings.set(binding.bindingId, result);
|
||||
return result;
|
||||
},
|
||||
invalidatedCall: (node: t.Node): boolean => {
|
||||
const cached = invalidatedCalls.get(node);
|
||||
if (cached !== undefined) return cached;
|
||||
const result = invalidatedOrigin(calls.get(node));
|
||||
invalidatedCalls.set(node, result);
|
||||
return result;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const identityFunction = (
|
||||
node: t.Node,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): boolean => {
|
||||
if (
|
||||
!t.isFunction(node) ||
|
||||
node.async ||
|
||||
node.generator ||
|
||||
node.params.length !== 1
|
||||
)
|
||||
return false;
|
||||
const parameter = node.params[0];
|
||||
const result = t.isBlockStatement(node.body)
|
||||
? node.body.body.length === 1 && t.isReturnStatement(node.body.body[0])
|
||||
? node.body.body[0].argument
|
||||
: undefined
|
||||
: node.body;
|
||||
return (
|
||||
t.isIdentifier(parameter) &&
|
||||
t.isIdentifier(result) &&
|
||||
resolveSemanticBindingState(state, parameter, parameter.name) !==
|
||||
undefined &&
|
||||
resolveSemanticBindingState(state, parameter, parameter.name) ===
|
||||
resolveSemanticBindingState(state, result, result.name)
|
||||
);
|
||||
};
|
||||
|
||||
const stableInitializer = (
|
||||
binding: JavaScriptSemanticBindingState | undefined,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
|
||||
@@ -391,7 +391,13 @@ export function* classifyParsedJavaScriptElectronBindingsSteps(
|
||||
? undefined
|
||||
: (exported ?? undefined);
|
||||
}
|
||||
const origin = semanticRequireOrigin(root, state)?.origin;
|
||||
const wrapped = interop.callOrigin(root);
|
||||
const origin =
|
||||
wrapped === undefined
|
||||
? semanticRequireOrigin(root, state)?.origin
|
||||
: collectedWrites && interop.invalidatedCall(root)
|
||||
? undefined
|
||||
: wrapped.origin;
|
||||
return origin !== undefined && ELECTRON_MODULE.test(origin.specifier)
|
||||
? electronExportPath(origin.importedPath)
|
||||
: undefined;
|
||||
@@ -442,7 +448,7 @@ const electronExport = (
|
||||
const reassigned = binding.definitions.some(
|
||||
({ kind }) => kind === "assignment",
|
||||
);
|
||||
const converted = reassigned ? interop.origin(binding) : undefined;
|
||||
const converted = interop.origin(binding);
|
||||
if (reassigned && converted === undefined) return null;
|
||||
const directOrigin = converted?.origin ?? bindingOrigin(binding, state);
|
||||
const [initializer] = binding.initializers;
|
||||
|
||||
@@ -169,17 +169,18 @@ describe("packaged Windows native admission", () => {
|
||||
}),
|
||||
).toMatchObject({
|
||||
available: false,
|
||||
retryable: true,
|
||||
reason: expect.stringContaining("private DACL: access denied"),
|
||||
});
|
||||
});
|
||||
|
||||
it("requires every inspected native fact", () => {
|
||||
const value = fixture();
|
||||
expect(
|
||||
loadWindowsNativeAuthority({
|
||||
...value.host,
|
||||
loadArtifact: () => ({ call: () => ({ privateDacl: true }) }),
|
||||
}).available,
|
||||
).toBe(false);
|
||||
const loaded = loadWindowsNativeAuthority({
|
||||
...value.host,
|
||||
loadArtifact: () => ({ call: () => ({ privateDacl: true }) }),
|
||||
});
|
||||
expect(loaded.available).toBe(false);
|
||||
expect(loaded).not.toHaveProperty("retryable");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -67,7 +67,12 @@ export interface WindowsNativeAuthority {
|
||||
/** Availability of the bundled native implementation, including load failures. */
|
||||
export type WindowsNativeLoadResult =
|
||||
| { readonly available: true; readonly authority: WindowsNativeAuthority }
|
||||
| { readonly available: false; readonly reason: string };
|
||||
| {
|
||||
readonly available: false;
|
||||
readonly reason: string;
|
||||
/** Only a failed native invocation can recover on a later query. */
|
||||
readonly retryable?: true;
|
||||
};
|
||||
|
||||
/** Trusted package reads and module loading, replaceable in loader tests. */
|
||||
export interface WindowsNativeLoadHost {
|
||||
@@ -106,7 +111,17 @@ export const loadWindowsNativeAuthority = (
|
||||
);
|
||||
assertWindowsX64Artifact(artifact);
|
||||
const binding = bindingSchema.parse(host.loadArtifact());
|
||||
const inspection = inspectionSchema.parse(binding.call("inspect", []));
|
||||
let observed: unknown;
|
||||
try {
|
||||
observed = binding.call("inspect", []);
|
||||
} catch (cause: unknown) {
|
||||
return {
|
||||
available: false,
|
||||
retryable: true,
|
||||
reason: `REA Windows native self-test failed: ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
};
|
||||
}
|
||||
const inspection = inspectionSchema.parse(observed);
|
||||
return { available: true, authority: { call: binding.call, inspection } };
|
||||
} catch (cause: unknown) {
|
||||
return {
|
||||
@@ -131,8 +146,10 @@ const assertWindowsX64Artifact = (bytes: Buffer): void => {
|
||||
|
||||
let cached: WindowsNativeLoadResult | undefined;
|
||||
|
||||
/** Load only the package-owned artifact, lazily and once per process. */
|
||||
/** Cache stable admission; let a later query retry failed owned inspection. */
|
||||
export const systemWindowsNativeAuthority = (): WindowsNativeLoadResult => {
|
||||
if (cached?.available === false && cached.retryable === true)
|
||||
cached = undefined;
|
||||
cached ??= loadWindowsNativeAuthority({
|
||||
platform: process.platform,
|
||||
architecture: process.arch,
|
||||
|
||||
Reference in New Issue
Block a user