fix(electron): support packaged app.asar pages and rewritten unpacked companions (#1400)
* fix(electron): resolve pages served from inside app.asar Packaged Electron applications load their renderer pages from file URLs inside app.asar. The host filesystem cannot stat those paths, so list_electron_targets excluded every such page as unsupported_url and inspect_electron_page could not select it. Resolve these URLs the way Electron's file protocol does: the first .asar path component that is a regular file is the archive, and the remainder must name a regular file in its header. Directories, links, and missing members stay rejected. Parsed headers are cached by archive identity. * fix(artifacts): extract and explain rewritten ASAR unpacked companions Packaging tools commonly sign or strip .asar.unpacked native binaries after writing the archive header, so their declared hashes no longer match. analyze_javascript_application already accepts integrity_policy, but extract_artifact did not, and inspect_artifact and extract_artifact still told callers to "get a fresh copy", which cannot help for a shipped app. - Accept integrity_policy on extract_artifact (MCP and CLI). The default still fails closed; record-and-continue writes the observed bytes and returns the extracted files' integrity_contradictions records. - Name the unpacked entry and the post-packaging cause in integrity failures, and point every operation that accepts integrity_policy at record-and-continue. - Report an active unpacked entry whose companion file is absent as unavailable with its logical path instead of a format failure. - Share one integrity_policy schema across the inventory, extraction, and JavaScript application inputs. * fix(electron): bound ASAR headers before allocation --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
import { rm, writeFile } from "node:fs/promises";
|
||||
import { mkdir, realpath, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import { createPackage } from "@electron/asar";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
@@ -199,6 +200,51 @@ describe("CdpElectronProvider target selection", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("CdpElectronProvider packaged pages", () => {
|
||||
it("lists and inspects packaged pages served from inside app.asar", async () => {
|
||||
const root = await createTestTempDirectory("rea-electron-asar-provider-");
|
||||
temporary.push(root);
|
||||
const source = join(root, "source");
|
||||
await mkdir(source);
|
||||
await writeFile(
|
||||
join(source, "index.html"),
|
||||
"<script src='app.js'></script>",
|
||||
);
|
||||
await writeFile(join(source, "app.js"), "export const app = true;");
|
||||
const archive = join(root, "app.asar");
|
||||
await createPackage(source, archive);
|
||||
const packaged = await realpath(archive);
|
||||
const browser = await startFakeCdpBrowser({
|
||||
electronFileUrl: `${pathToFileURL(join(archive, "index.html")).href}?isBookDoubleClicked=0#/library`,
|
||||
});
|
||||
browsers.push(browser);
|
||||
const provider = new CdpElectronProvider();
|
||||
const listed = await provider.listTargets(
|
||||
listElectronTargetsInputSchema.parse({ cdp_endpoint: browser.endpoint }),
|
||||
);
|
||||
if (!listed.ok) throw listed.error;
|
||||
expect(listed.value.targets).toEqual([
|
||||
expect.objectContaining({
|
||||
target_id: "electron-page",
|
||||
file_path: join(packaged, "index.html"),
|
||||
}),
|
||||
]);
|
||||
|
||||
const inspected = await provider.inspectPage(
|
||||
inspectElectronPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
target_id: "electron-page",
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
if (!inspected.ok) throw inspected.error;
|
||||
expect(inspected.value.target.file_path).toBe(join(packaged, "index.html"));
|
||||
expect(inspected.value.scripts.items).toEqual([
|
||||
expect.objectContaining({ file_path: join(packaged, "app.js") }),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("CdpElectronProvider capture", () => {
|
||||
it.each([{}, { scriptSource: null }, { scriptSource: 123 }])(
|
||||
"rejects malformed Electron source replies instead of inventing source: %j",
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { mkdir, symlink, writeFile } from "node:fs/promises";
|
||||
import { mkdir, realpath, symlink, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import { createPackageWithOptions } from "@electron/asar";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
@@ -48,6 +49,43 @@ describe("Electron file scope", () => {
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("resolves regular files Electron serves from inside an ASAR archive", async () => {
|
||||
const root = await createTestTempDirectory("rea-electron-asar-scope-");
|
||||
const source = join(root, "source");
|
||||
await mkdir(join(source, "build", "static"), { recursive: true });
|
||||
await mkdir(join(source, "native"));
|
||||
await writeFile(join(source, "build", "index.html"), "<p>packed</p>");
|
||||
await writeFile(join(source, "build", "static", "app.js"), "app();");
|
||||
await writeFile(join(source, "native", "addon.node"), "native");
|
||||
await writeFile(join(source, "notes.txt"), "plain");
|
||||
const archive = join(root, "app.asar");
|
||||
await createPackageWithOptions(source, archive, { unpack: "*.node" });
|
||||
const canonical = await realpath(archive);
|
||||
const member = (...parts: string[]) =>
|
||||
pathToFileURL(join(archive, ...parts)).href;
|
||||
|
||||
expect(await authorizedElectronFile(member("build", "index.html"))).toBe(
|
||||
join(canonical, "build", "index.html"),
|
||||
);
|
||||
expect(
|
||||
await authorizedElectronFile(
|
||||
`${member("build", "static", "app.js")}?isBookDoubleClicked=0#/library`,
|
||||
),
|
||||
).toBe(join(canonical, "build", "static", "app.js"));
|
||||
expect(await authorizedElectronFile(member("native", "addon.node"))).toBe(
|
||||
join(canonical, "native", "addon.node"),
|
||||
);
|
||||
expect(await authorizedElectronFile(member("build"))).toBeUndefined();
|
||||
expect(
|
||||
await authorizedElectronFile(member("build", "missing.html")),
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
await authorizedElectronFile(
|
||||
pathToFileURL(join(source, "notes.txt", "index.html")).href,
|
||||
),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("accepts file URLs with long query text", async () => {
|
||||
const root = await createTestTempDirectory("rea-electron-long-url-");
|
||||
const path = join(root, "index.html");
|
||||
@@ -56,4 +94,29 @@ describe("Electron file scope", () => {
|
||||
|
||||
await expect(authorizedElectronFile(value)).resolves.toBe(path);
|
||||
});
|
||||
it("resolves an archive beneath an ASAR-named directory and rejects oversized declared headers", async () => {
|
||||
const root = await createTestTempDirectory("rea-electron-header-");
|
||||
const source = join(root, "source");
|
||||
await mkdir(source);
|
||||
await writeFile(join(source, "index.html"), "page");
|
||||
const parent = join(root, "parent.asar");
|
||||
await mkdir(parent);
|
||||
const archive = join(parent, "app.asar");
|
||||
await createPackageWithOptions(source, archive, {});
|
||||
expect(
|
||||
await authorizedElectronFile(
|
||||
pathToFileURL(join(archive, "index.html")).href,
|
||||
),
|
||||
).toBe(join(await realpath(archive), "index.html"));
|
||||
const malformed = join(root, "bad.asar");
|
||||
const header = Buffer.alloc(16);
|
||||
header.writeUInt32LE(4, 0);
|
||||
header.writeUInt32LE(0x40000000, 4);
|
||||
await writeFile(malformed, header);
|
||||
expect(
|
||||
await authorizedElectronFile(
|
||||
pathToFileURL(join(malformed, "index.html")).href,
|
||||
),
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -18,6 +18,13 @@ import { ARTIFACT_COMPARISON_EXAMPLE } from "../../../src/contracts/artifactComp
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
const integrityMessage = (unpacked: boolean): string =>
|
||||
`${
|
||||
unpacked
|
||||
? "Declared ASAR integrity for unpacked entry main.js contradicts its companion file; packaging tools commonly sign or strip unpacked native binaries after writing the archive."
|
||||
: "Artifact bytes contradict declared integrity."
|
||||
} If expected, rerun inspect_artifact with integrity_policy=record-and-continue (CLI: --integrity-policy record-and-continue) to retain observed bytes as untrusted; otherwise get a fresh copy.`;
|
||||
|
||||
it.each([
|
||||
{ unpacked: false, label: "embedded" },
|
||||
{ unpacked: true, label: "unpacked" },
|
||||
@@ -69,8 +76,7 @@ it.each([
|
||||
error: {
|
||||
code: "artifact_integrity_mismatch",
|
||||
category: "integrity_mismatch",
|
||||
message:
|
||||
"Artifact is invalid or has changed. Get a fresh copy and try again.",
|
||||
message: integrityMessage(unpacked),
|
||||
details: {
|
||||
logical_path: "main.js",
|
||||
declared_sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
|
||||
@@ -78,10 +84,7 @@ it.each([
|
||||
unpacked,
|
||||
},
|
||||
retryable: false,
|
||||
remediation: {
|
||||
action:
|
||||
"Artifact is invalid or has changed. Get a fresh copy and try again.",
|
||||
},
|
||||
remediation: { action: integrityMessage(unpacked) },
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { readFile, rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
||||
import { createStrippedAsarAddon } from "../../fixtures/strippedAsarAddon.js";
|
||||
|
||||
const openArchive = async (archive: string): Promise<Client> => {
|
||||
const session = createTestBinarySession(new ArtifactProvider(process.env));
|
||||
const server = createServer({ kind: "session", session });
|
||||
const client = new Client({ name: "asar-unpacked-extraction", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
onTestFinished(async () => {
|
||||
await Promise.allSettled([client.close(), server.close(), session.close()]);
|
||||
});
|
||||
const opened = await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: archive },
|
||||
});
|
||||
expect(opened.isError).not.toBe(true);
|
||||
return client;
|
||||
};
|
||||
|
||||
it("extracts a rewritten unpacked companion only when the caller records the mismatch", async () => {
|
||||
const { archive, addon, stripped } = await createStrippedAsarAddon();
|
||||
const client = await openArchive(archive);
|
||||
|
||||
const strict = await client.callTool({
|
||||
name: "extract_artifact",
|
||||
arguments: {},
|
||||
});
|
||||
expect(parseMcpToolError(strict).error).toMatchObject({
|
||||
code: "artifact_integrity_mismatch",
|
||||
message: expect.stringContaining(
|
||||
`Declared ASAR integrity for unpacked entry ${addon} contradicts its companion file; packaging tools commonly sign or strip unpacked native binaries after writing the archive. If expected, rerun extract_artifact with integrity_policy=record-and-continue`,
|
||||
),
|
||||
details: { logical_path: addon, unpacked: true },
|
||||
});
|
||||
|
||||
const continued = await client.callTool({
|
||||
name: "extract_artifact",
|
||||
arguments: { integrity_policy: "record-and-continue" },
|
||||
});
|
||||
expect(continued.isError, JSON.stringify(continued)).not.toBe(true);
|
||||
const evidence = parseEvidence(continued.structuredContent);
|
||||
expect(evidence.parameters).toMatchObject({
|
||||
integrity_policy: "record-and-continue",
|
||||
});
|
||||
const result = z
|
||||
.object({
|
||||
output_root: z.string(),
|
||||
integrity_contradictions: z.array(
|
||||
z.object({ logical_path: z.string(), trust: z.string() }),
|
||||
),
|
||||
limitations: z.array(z.string()),
|
||||
})
|
||||
.parse(evidence.normalized_result);
|
||||
onTestFinished(() =>
|
||||
rm(result.output_root, { recursive: true, force: true }),
|
||||
);
|
||||
expect(await readFile(join(result.output_root, addon))).toEqual(stripped);
|
||||
expect(result.integrity_contradictions).toEqual([
|
||||
{ logical_path: addon, trust: "observed-untrusted" },
|
||||
]);
|
||||
expect(result.limitations).toContain(
|
||||
"1 extracted file(s) contradict declared integrity metadata; their bytes are observed-untrusted.",
|
||||
);
|
||||
});
|
||||
|
||||
it("names a missing unpacked companion instead of reporting a changed artifact", async () => {
|
||||
const { archive, addon } = await createStrippedAsarAddon();
|
||||
await rm(join(`${archive}.unpacked`, addon));
|
||||
const client = await openArchive(archive);
|
||||
|
||||
const extracted = await client.callTool({
|
||||
name: "extract_artifact",
|
||||
arguments: {},
|
||||
});
|
||||
expect(parseMcpToolError(extracted).error).toMatchObject({
|
||||
code: "artifact_operation_failed",
|
||||
category: "unavailable",
|
||||
message: `ASAR unpacked companion bytes are unavailable for ${addon}. Select the archive in place with its .unpacked directory beside it, then retry.`,
|
||||
details: { logical_path: addon, unpacked: true },
|
||||
});
|
||||
});
|
||||
@@ -121,11 +121,8 @@ it("ignores unavailable members of a nested ASAR but refuses them as active entr
|
||||
throw new Error("Unavailable active ASAR member must fail extraction");
|
||||
expect(projectAnalysisError(activeResult.error)).toMatchObject({
|
||||
code: "artifact_operation_failed",
|
||||
details: {
|
||||
operation: "extract_artifact",
|
||||
reason: "format",
|
||||
detail: expect.stringContaining("native/addon.node"),
|
||||
},
|
||||
category: "unavailable",
|
||||
details: { logical_path: "native/addon.node", unpacked: true },
|
||||
});
|
||||
await expect(access(activeOutput)).rejects.toThrow();
|
||||
});
|
||||
@@ -139,6 +136,7 @@ const inventoriedExtraction = async (source: string, output: string) => {
|
||||
inputFormat: "asar",
|
||||
outputRoot: output,
|
||||
environment: process.env,
|
||||
integrityPolicy: "fail",
|
||||
},
|
||||
source,
|
||||
snapshot,
|
||||
|
||||
Reference in New Issue
Block a user