Merge remote-tracking branch 'origin/main'
This commit is contained in:
@@ -3,6 +3,37 @@ import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { captureWebScreenshotInputSchema } from "../../../src/domain/webScreenshot.js";
|
||||
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
describe("screenshot committed document identity", () => {
|
||||
it.each([
|
||||
{ offset: 8, value: 14 },
|
||||
{ offset: 16, value: 0x8000_0000 },
|
||||
{ offset: 20, value: 0x8000_0000 },
|
||||
])("rejects invalid screenshot IHDR metadata", async ({ offset, value }) => {
|
||||
const bytes = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jv4sAAAAASUVORK5CYII=",
|
||||
"base64",
|
||||
);
|
||||
bytes.writeUInt32BE(value, offset);
|
||||
const browser = await startFakeCdpBrowser({
|
||||
commandResult: ({ method }) =>
|
||||
method === "Page.captureScreenshot"
|
||||
? { data: bytes.toString("base64") }
|
||||
: undefined,
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
await browser.close();
|
||||
});
|
||||
const result = await new CdpBrowserProvider().captureScreenshot(
|
||||
captureWebScreenshotInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
}),
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { reason: "protocol_error" },
|
||||
});
|
||||
});
|
||||
it.each(["loader-main", "loader-reloaded"])(
|
||||
"distinguishes %s for the same URL",
|
||||
async (screenshotDocumentLoader) => {
|
||||
|
||||
@@ -7,6 +7,9 @@ import { execFile } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { webNetworkCaptureSchema } from "../../../src/domain/webNetworkCapture.js";
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
const entrypoint = fileURLToPath(
|
||||
new URL("../../../scripts/rea.mjs", import.meta.url),
|
||||
);
|
||||
@@ -41,6 +44,91 @@ const cli = async (
|
||||
};
|
||||
import { historicalHar } from "../../fixtures/historicalHar.js";
|
||||
|
||||
it("excludes declared binary lengths through CLI, MCP and retained capture pages", async () => {
|
||||
const root = await createTestTempDirectory("rea-har-byte-length-");
|
||||
const path = join(root, "capture.har");
|
||||
const fixture = historicalHar();
|
||||
const entry = fixture.log.entries[0];
|
||||
if (entry === undefined) throw new Error("fixture missing");
|
||||
const body = Buffer.alloc(12_345, "A");
|
||||
const content = body.toString("base64");
|
||||
const digest = createHash("sha256").update(body).digest("hex");
|
||||
await writeFile(
|
||||
path,
|
||||
JSON.stringify({
|
||||
log: {
|
||||
...fixture.log,
|
||||
entries: [
|
||||
{
|
||||
...entry,
|
||||
response: {
|
||||
...entry.response,
|
||||
content: {
|
||||
size: 99,
|
||||
mimeType: "text/plain",
|
||||
encoding: "base64",
|
||||
text: content,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const args = { capture_path: path, format: "har" };
|
||||
const control = await call("inspect_web_network_capture", args);
|
||||
expect(control.isError).not.toBe(true);
|
||||
const retained = parseEvidence(control.structuredContent);
|
||||
const controlCapture = webNetworkCaptureSchema.parse(
|
||||
retained.normalized_result,
|
||||
);
|
||||
expect(controlCapture.records[0]?.binary_fields[0]).toMatchObject({
|
||||
state: "retained",
|
||||
bytes: body.length,
|
||||
content_base64: content,
|
||||
sha256: digest,
|
||||
});
|
||||
for (const literal of ["12345", "2345"]) {
|
||||
// Only the derived count matches, so this cannot pass via another exclusion.
|
||||
expect(content).not.toContain(literal);
|
||||
expect(digest).not.toContain(literal);
|
||||
const fromCli = await cli(path, "har", ["--sensitive-value", literal]);
|
||||
expect(fromCli.ok, fromCli.stdout).toBe(true);
|
||||
const evidence = parseEvidence(JSON.parse(fromCli.stdout));
|
||||
const response = await call("inspect_web_network_capture", {
|
||||
...args,
|
||||
sensitive_values: [literal],
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
const fromMcp = parseEvidence(response.structuredContent);
|
||||
expect(fromMcp.normalized_result).toEqual(evidence.normalized_result);
|
||||
const capture = webNetworkCaptureSchema.parse(evidence.normalized_result);
|
||||
expect(capture.records[0]?.reported).toMatchObject({
|
||||
response: { content: { size: 99, text: null } },
|
||||
});
|
||||
expect(capture.records[0]?.binary_fields[0]).toEqual({
|
||||
pointer: "/response/content/text",
|
||||
representation: "har-base64-content",
|
||||
state: "redacted",
|
||||
bytes: null,
|
||||
content_base64: null,
|
||||
sha256: null,
|
||||
});
|
||||
for (const detail of ["preview", "complete"]) {
|
||||
const page = await call("inspect_analysis_view", {
|
||||
source: { kind: "retained-evidence", evidence_id: fromMcp.evidence_id },
|
||||
view: { kind: "capture", detail },
|
||||
});
|
||||
expect(page.isError).not.toBe(true);
|
||||
const result = parseEvidence(page.structuredContent);
|
||||
expect(result.normalized_result).toMatchObject({
|
||||
items: [{ binary_fields: [{ state: "redacted", bytes: null }] }],
|
||||
});
|
||||
}
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it("reads actual upstream HAR packages in an owned process and retains selected producer order", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-history-har-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
type ApplicationVersionComparisonResult,
|
||||
} from "../../../src/domain/javascript/javascriptApplicationVersionComparisonSchemas.js";
|
||||
import { javascriptRuntimeReconciliationResultSchema } from "../../../src/domain/javascript/javascriptRuntimeReconciliationSchemas.js";
|
||||
import { electronPageInspectionSchema } from "../../../src/domain/javascript/electronObservation.js";
|
||||
import { compareJavaScriptApplicationVersions } from "../../../src/domain/javascript/javascriptApplicationVersionComparison.js";
|
||||
import { createJavaScriptApplicationGraph } from "../../../src/domain/javascript/javascriptApplicationGraph.js";
|
||||
import { traceApplicationFeature } from "../../../src/domain/javascript/javascriptFeatureTrace.js";
|
||||
@@ -444,6 +445,73 @@ describe("JavaScript application workflow error diagnostics", () => {
|
||||
});
|
||||
|
||||
describe("JavaScript runtime reconciliation local paths", () => {
|
||||
it.each([
|
||||
{
|
||||
name: "case-sensitive POSIX input root",
|
||||
root: null,
|
||||
path: "/applications/Example.app/Contents/Resources/app/renderer.js",
|
||||
status: "unknown",
|
||||
},
|
||||
{
|
||||
name: "case-sensitive POSIX mapping root",
|
||||
root: "/runtime/App",
|
||||
path: "/runtime/app/renderer.js",
|
||||
status: "unknown",
|
||||
},
|
||||
{
|
||||
name: "matching POSIX mapping root",
|
||||
root: "/runtime/App",
|
||||
path: "/runtime/App/renderer.js",
|
||||
status: "matched",
|
||||
},
|
||||
{
|
||||
name: "case-insensitive Windows mapping root",
|
||||
root: String.raw`C:\runtime\App`,
|
||||
path: String.raw`c:\runtime\app\renderer.js`,
|
||||
status: "matched",
|
||||
},
|
||||
])("uses $name on every host", ({ root, path, status }) => {
|
||||
const base = JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE;
|
||||
const original = base.runtime_observations[0]!;
|
||||
const inspection = electronPageInspectionSchema.parse(
|
||||
original.normalized_result,
|
||||
);
|
||||
const runtime = createEvidence(undefined, original.provider, {
|
||||
predicateType: original.predicate_type,
|
||||
operation: original.operation,
|
||||
parameters: { ...original.parameters, include_script_sources: false },
|
||||
result: {
|
||||
...inspection,
|
||||
scripts: {
|
||||
...inspection.scripts,
|
||||
items: inspection.scripts.items.map((script) => ({
|
||||
...script,
|
||||
file_path: path,
|
||||
source: { included: false, reason: "not-requested" },
|
||||
})),
|
||||
},
|
||||
},
|
||||
confidence: original.confidence,
|
||||
authority: original.authority,
|
||||
});
|
||||
const reconciled = reconcileJavaScriptRuntimeEvidence({
|
||||
static_layers: base.static_layers.map((layer) => ({
|
||||
...layer,
|
||||
runtime_mappings: root === null ? [] : [{ kind: "file-root", root }],
|
||||
})),
|
||||
runtime_observations: [runtime],
|
||||
});
|
||||
if (!reconciled.ok) throw reconciled.error;
|
||||
const result = javascriptRuntimeReconciliationResultSchema.parse(
|
||||
reconciled.value.normalized_result,
|
||||
);
|
||||
expect(
|
||||
result.reconciliations.find(
|
||||
({ entity_kind }) => entity_kind === "script",
|
||||
),
|
||||
).toMatchObject({ status });
|
||||
});
|
||||
|
||||
it("resolves relative file mapping roots before deriving result Evidence", () => {
|
||||
const absoluteRoot = resolve(process.cwd(), "runtime-cache-fixture");
|
||||
const relativeRoot = relative(process.cwd(), absoluteRoot);
|
||||
|
||||
@@ -6,6 +6,31 @@ import { expect, it } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { importReferenceSource } from "../../support/referenceSourceResourceScope.js";
|
||||
|
||||
it("imports valid CommonJS wrapper syntax without inventing a parse failure", async () => {
|
||||
const root = await createTestTempDirectory("rea-reference-commonjs-mode-");
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(root, "main.cjs"),
|
||||
'void new.target; require("./dep.cjs"); return;\n',
|
||||
),
|
||||
writeFile(join(root, "dep.cjs"), "module.exports = 1;\n"),
|
||||
]);
|
||||
const imported = await importReferenceSource({
|
||||
root,
|
||||
caller: "native-commonjs-source",
|
||||
policy: { secretPatterns: [] },
|
||||
});
|
||||
if (!imported.ok) throw imported.error;
|
||||
expect(imported.value.parse_failures).toEqual([]);
|
||||
expect(imported.value.relationships).toContainEqual({
|
||||
from_path: "main.cjs",
|
||||
to: "dep.cjs",
|
||||
kind: "requires",
|
||||
resolution: "internal",
|
||||
parse_state: "parsed",
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["main.ts", "dep.js", "dep.ts"],
|
||||
["main.mts", "dep.mjs", "dep.mts"],
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, onTestFinished, vi } from "vitest";
|
||||
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import {
|
||||
createDeferred,
|
||||
createTestBinarySession,
|
||||
} from "../../fixtures/binarySession.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const connectImportSession = async () => {
|
||||
const root = await createTestTempDirectory("rea-mcp-import-lifecycle-");
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("Evidence import must not start a binary provider");
|
||||
});
|
||||
const server = createServer({ kind: "session", session });
|
||||
const client = new Client({
|
||||
name: "evidence-import-lifecycle",
|
||||
version: "1",
|
||||
});
|
||||
const readCompleted = createDeferred<void>();
|
||||
const releaseRead = createDeferred<void>();
|
||||
const originalFileClose = OwnedFileHandle.prototype.close;
|
||||
vi.spyOn(OwnedFileHandle.prototype, "close").mockImplementationOnce(
|
||||
async function (this: OwnedFileHandle) {
|
||||
await originalFileClose.call(this);
|
||||
readCompleted.resolve();
|
||||
await releaseRead.promise;
|
||||
},
|
||||
);
|
||||
const closeStarted = createDeferred<void>();
|
||||
const originalSessionClose = session.close.bind(session);
|
||||
const events: string[] = [];
|
||||
vi.spyOn(session, "close").mockImplementation((...args) => {
|
||||
const closing = originalSessionClose(...args);
|
||||
closeStarted.resolve();
|
||||
return closing.then((result) => {
|
||||
events.push("close");
|
||||
return result;
|
||||
});
|
||||
});
|
||||
const originalImport = session.importEvidenceBundle.bind(session);
|
||||
vi.spyOn(session, "importEvidenceBundle").mockImplementation((bundle) => {
|
||||
const imported = originalImport(bundle);
|
||||
events.push("import");
|
||||
return imported;
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
releaseRead.resolve();
|
||||
vi.restoreAllMocks();
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
const laterImportDispatched = createDeferred<void>();
|
||||
let importsDispatched = 0;
|
||||
const send = clientTransport.send.bind(clientTransport);
|
||||
vi.spyOn(clientTransport, "send").mockImplementation(
|
||||
async (message, ...args) => {
|
||||
await send(message, ...args);
|
||||
if (
|
||||
"method" in message &&
|
||||
message.method === "tools/call" &&
|
||||
message.params?.name === "import_evidence_bundle"
|
||||
) {
|
||||
importsDispatched += 1;
|
||||
if (importsDispatched === 2) laterImportDispatched.resolve();
|
||||
}
|
||||
},
|
||||
);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const importBundle = async (operation: string) => {
|
||||
const record = createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{ operation, parameters: {}, result: { retained: operation } },
|
||||
);
|
||||
const path = join(root, `${operation}.json`);
|
||||
await writeFile(path, JSON.stringify(createEvidenceBundle([record])));
|
||||
return client.callTool({
|
||||
name: "import_evidence_bundle",
|
||||
arguments: { path },
|
||||
});
|
||||
};
|
||||
return {
|
||||
client,
|
||||
session,
|
||||
events,
|
||||
importBundle,
|
||||
readCompleted: readCompleted.promise,
|
||||
closeStarted: closeStarted.promise,
|
||||
laterImportDispatched: laterImportDispatched.promise,
|
||||
releaseRead: () => releaseRead.resolve(),
|
||||
};
|
||||
};
|
||||
|
||||
it("drains a file import before close_binary clears the session", async () => {
|
||||
const fixture = await connectImportSession();
|
||||
const importing = fixture.importBundle("before_close");
|
||||
await fixture.readCompleted;
|
||||
const closing = fixture.client.callTool({
|
||||
name: "close_binary",
|
||||
arguments: {},
|
||||
});
|
||||
await fixture.closeStarted;
|
||||
await fixture.client.ping();
|
||||
fixture.releaseRead();
|
||||
const [imported, closed] = await Promise.all([importing, closing]);
|
||||
|
||||
expect(imported.isError, JSON.stringify(imported)).not.toBe(true);
|
||||
expect(imported.structuredContent).toMatchObject({
|
||||
result: { imported: 1, unknowns_added: 0, total: 1 },
|
||||
});
|
||||
expect(closed.isError, JSON.stringify(closed)).not.toBe(true);
|
||||
expect(fixture.events).toEqual(["import", "close"]);
|
||||
expect(fixture.session.exportEvidenceBundle().records).toEqual([]);
|
||||
await fixture.client.ping();
|
||||
});
|
||||
|
||||
it("admits a later import after close_binary without retaining the earlier bundle", async () => {
|
||||
const fixture = await connectImportSession();
|
||||
const earlier = fixture.importBundle("before_close");
|
||||
await fixture.readCompleted;
|
||||
const closing = fixture.client.callTool({
|
||||
name: "close_binary",
|
||||
arguments: {},
|
||||
});
|
||||
await fixture.closeStarted;
|
||||
const later = fixture.importBundle("after_close");
|
||||
await fixture.laterImportDispatched;
|
||||
await fixture.client.ping();
|
||||
fixture.releaseRead();
|
||||
const results = await Promise.all([earlier, closing, later]);
|
||||
|
||||
for (const result of results)
|
||||
expect(result.isError, JSON.stringify(result)).not.toBe(true);
|
||||
expect(results[2]?.structuredContent).toMatchObject({
|
||||
result: { imported: 1, unknowns_added: 0, total: 1 },
|
||||
});
|
||||
expect(fixture.events).toEqual(["import", "close", "import"]);
|
||||
expect(
|
||||
fixture.session
|
||||
.exportEvidenceBundle()
|
||||
.records.map((record) => record.operation),
|
||||
).toEqual(["after_close"]);
|
||||
await fixture.client.ping();
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { parseJavaScriptSource } from "../../../src/domain/javascript/javascriptSourceParser.js";
|
||||
import { processTest } from "../../support/process/processFixture.js";
|
||||
|
||||
for (const source of [
|
||||
"return;",
|
||||
"void new.target;",
|
||||
"var await = 1; return;",
|
||||
"with ({ value: 1 }) { void value; } void new.target;",
|
||||
]) {
|
||||
processTest(
|
||||
`accepts Node CommonJS syntax while retaining module errors: ${source}`,
|
||||
async ({ processes }) => {
|
||||
const commonjs = await processes.run(
|
||||
process.execPath,
|
||||
["--check", "--input-type=commonjs"],
|
||||
{ input: source, timeoutMs: 5_000 },
|
||||
);
|
||||
expect(commonjs.exitCode).toBe(0);
|
||||
const module = await processes.run(
|
||||
process.execPath,
|
||||
["--check", "--input-type=module"],
|
||||
{ input: source, timeoutMs: 5_000 },
|
||||
);
|
||||
expect(module.exitCode).not.toBe(0);
|
||||
|
||||
const parsed = parseJavaScriptSource(source, "main.cjs");
|
||||
expect(parsed).not.toBeNull();
|
||||
expect(parsed?.errors).toEqual([]);
|
||||
expect(
|
||||
parseJavaScriptSource(source, "main.mjs")?.errors.length,
|
||||
).toBeGreaterThan(0);
|
||||
expect(
|
||||
parseJavaScriptSource(source, "main.mts")?.errors.length,
|
||||
).toBeGreaterThan(0);
|
||||
},
|
||||
);
|
||||
}
|
||||
+36
@@ -4,6 +4,7 @@
|
||||
#include <winioctl.h>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cwchar>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
@@ -33,6 +34,41 @@ int wmain(int count, wchar_t** args) {
|
||||
value(L"REA_\u00df") == expectedSharp && value(L"REA_SS") == L"double" ? "true" : "false");
|
||||
return 0;
|
||||
}
|
||||
if ((count == 2 || count == 3) && std::wstring(args[1]) == L"affinity") {
|
||||
// Without a process id this observes itself, which is what an owned child
|
||||
// reports. With one it observes that process, so a caller's own affinity is
|
||||
// read from the process that spawns the child rather than from a separate
|
||||
// probe Windows may place in another processor group.
|
||||
HANDLE opened = nullptr;
|
||||
if (count == 3) {
|
||||
opened = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE,
|
||||
static_cast<DWORD>(std::wcstoul(args[2], nullptr, 10)));
|
||||
if (!opened) return 9;
|
||||
}
|
||||
const HANDLE target = opened ? opened : GetCurrentProcess();
|
||||
DWORD_PTR affinity = 0, systemAffinity = 0;
|
||||
USHORT groupCount = 1;
|
||||
USHORT groups[1]{};
|
||||
const bool read = GetProcessAffinityMask(target, &affinity, &systemAffinity) != 0;
|
||||
const bool single = read && GetProcessGroupAffinity(target, &groupCount, groups) && groupCount == 1;
|
||||
if (opened) CloseHandle(opened);
|
||||
if (!read) return 8;
|
||||
// A mask can set bits above JavaScript's safe-integer range, so masks cross
|
||||
// as fixed-width hexadecimal strings and are compared without rounding. The
|
||||
// group's own active set distinguishes an unconstrained process from one
|
||||
// deliberately pinned to fewer processors.
|
||||
auto mask = [](DWORD_PTR value, char* text) {
|
||||
std::snprintf(text, 19, "0x%08lX%08lX", static_cast<unsigned long>(value >> 32),
|
||||
static_cast<unsigned long>(value & 0xFFFFFFFFu));
|
||||
return text;
|
||||
};
|
||||
char affinityText[19]{}, systemText[19]{};
|
||||
std::printf("{\"affinityMask\":\"%s\",\"systemMask\":\"%s\","
|
||||
"\"singleProcessorGroup\":%s,\"processorGroup\":%u}\n",
|
||||
mask(affinity, affinityText), mask(systemAffinity, systemText),
|
||||
single ? "true" : "false", single ? static_cast<unsigned>(groups[0]) : 0u);
|
||||
return 0;
|
||||
}
|
||||
if (count == 4 && std::wstring(args[1]) == L"reparse-directory") {
|
||||
// Only the conformance lane's disposable, nonempty source directory is used.
|
||||
const auto substitute = L"\\??\\" + std::wstring(args[3]);
|
||||
|
||||
Reference in New Issue
Block a user