Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0d44fe8f5 | ||
|
|
11c188523a | ||
|
|
794debe565 | ||
|
|
f379bc3882 | ||
|
|
97b76aa20a | ||
|
|
8ea0432ffc | ||
|
|
b9d9a474cf | ||
|
|
b88cdc248a | ||
|
|
c039dd81d5 | ||
|
|
58d23e42b6 |
@@ -72,5 +72,3 @@ Thumbs.db
|
||||
|
||||
# Complete static website output, including generated language editions.
|
||||
website/_site/
|
||||
# Temporary translation output prepared before replacing the complete site.
|
||||
website/.i18n-*/
|
||||
|
||||
@@ -93,7 +93,7 @@ def project_record(state, secrets):
|
||||
safe_bytes, credential_url = transport_value(value, path, transport_url)
|
||||
content_base64 = base64.b64encode(value).decode("ascii")
|
||||
digest = hashlib.sha256(value).hexdigest()
|
||||
hidden = any(secret in value or secret in safe_bytes for secret in byte_secrets) or any(secret in content_base64 or secret in digest or secret in str(len(value)) for secret in secrets)
|
||||
hidden = any(secret in value or secret in safe_bytes for secret in byte_secrets) or any(secret in content_base64 or secret in digest for secret in secrets)
|
||||
safe_text = None
|
||||
try:
|
||||
safe_text = safe_bytes.decode("utf-8", errors="strict")
|
||||
|
||||
@@ -174,7 +174,7 @@ Resolution follows dyld:
|
||||
- `@rpath` tries each `LC_RPATH` of the loading image first, then those of the
|
||||
image that loaded it, up to the process root.
|
||||
- Dependencies load dependents-first in load-command order, and each image
|
||||
loads once per process. A later @rpath request whose install name matches an
|
||||
loads once per process. A later request whose install name matches an
|
||||
already loaded image reuses it.
|
||||
- Symlinks such as `Versions/Current` are followed inside the analyzed root.
|
||||
An escape through `..` or an absolute link is `escapes-target`.
|
||||
|
||||
@@ -153,12 +153,8 @@ the private runtime, isolating Ghidra preferences, logs, and caches.
|
||||
Process creation assigns a suspended child atomically to an owned Job Object.
|
||||
Membership and kill-on-owner-close policy are verified before resume.
|
||||
Breakaway is disabled. Only the child's default file owner is normalized;
|
||||
the caller token stays unchanged. Caller priority is preserved, and caller CPU
|
||||
affinity whenever the caller and the child share a processor group. A child that
|
||||
Windows places in another group keeps that group's default when the caller asked
|
||||
for no bound of its own; a caller pinned to fewer processors than its group
|
||||
holds is refused there rather than widened.
|
||||
Close, cancellation, timeout, startup failure, and provider failure
|
||||
the caller token stays unchanged. Caller CPU affinity and priority are
|
||||
preserved. Close, cancellation, timeout, startup failure, and provider failure
|
||||
terminate the job and verify all members have settled before runtime cleanup.
|
||||
Cleanup removes admitted objects by handle and unlinks reparse entries without
|
||||
following their targets. Abrupt owner death kills the job but can leave
|
||||
|
||||
@@ -69,22 +69,10 @@ without this lane reports Windows native controls as unavailable.
|
||||
limits only for its JavaScript helpers when running on Bun, which ignores
|
||||
their V8 heap flags; Node.js launches are unchanged.
|
||||
- Only the suspended child's default file owner is normalized. Caller token
|
||||
privileges and ownership remain unchanged. Caller process priority is
|
||||
preserved in the child, and caller CPU affinity whenever both occupy the same
|
||||
processor group. Windows chooses a new process's group itself and rejects a
|
||||
mask belonging to another group, so a child placed elsewhere keeps that
|
||||
group's default when the caller asked for no bound of its own. A caller
|
||||
deliberately pinned to fewer processors than its group holds is a constraint
|
||||
such a child cannot express, and is refused rather than widened to that
|
||||
group's default. A mask covering its group's whole active set does not
|
||||
distinguish a caller Windows placed in that group from one that selected the
|
||||
group deliberately, so such a child can still be placed elsewhere: its
|
||||
processor count stays bounded, its group placement is not preserved, and
|
||||
neither that case nor the refusal above has a verification lane, because both
|
||||
need a host whose processors span more than one group.
|
||||
Environment names are sorted and deduplicated using Windows
|
||||
ordinal comparison, preserving their native Unicode semantics and
|
||||
caller-selected values.
|
||||
privileges and ownership remain unchanged. Caller CPU affinity and process
|
||||
priority are preserved in the child. Environment names are sorted and
|
||||
deduplicated using Windows ordinal comparison, preserving their native Unicode
|
||||
semantics and caller-selected values.
|
||||
- Cleanup walks locked directory objects, removes files by handle, and unlinks
|
||||
reparse entries without traversing their targets. Failed removal retains the
|
||||
root and ancestor leases for retry; a partially removed runtime accepts only
|
||||
|
||||
@@ -68,18 +68,6 @@ static ULONGLONG jobMemoryLimit(napi_env env, napi_value value) {
|
||||
return limit;
|
||||
}
|
||||
|
||||
// An affinity mask is meaningful only inside one processor group, so only a
|
||||
// process occupying exactly one group has a group a child can inherit. A
|
||||
// process whose threads span groups, or whose membership cannot be read, has no
|
||||
// single group.
|
||||
static bool singleProcessorGroup(HANDLE process, USHORT& group) {
|
||||
USHORT count = 1;
|
||||
std::array<USHORT, 1> groups{};
|
||||
if (!GetProcessGroupAffinity(process, &count, groups.data()) || count != 1) return false;
|
||||
group = groups[0];
|
||||
return true;
|
||||
}
|
||||
|
||||
static void pipe(Handle& read, Handle& write, bool parentReads = true) {
|
||||
SECURITY_ATTRIBUTES attributes{sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE};
|
||||
HANDLE rawRead, rawWrite;
|
||||
@@ -180,27 +168,11 @@ std::unique_ptr<Process> spawnProcess(const std::wstring& command, const std::ws
|
||||
TOKEN_OWNER owner{reinterpret_cast<TOKEN_USER*>(tokenUser.data())->User.Sid};
|
||||
require(SetTokenInformation(token.get(), TokenOwner, &owner, sizeof(owner)),
|
||||
"Set suspended process file owner failed", command);
|
||||
// A mask names processors inside one processor group, and Windows assigns a
|
||||
// new process to a group of its own choosing, so a mask belonging to another
|
||||
// group is rejected (ERROR_INVALID_PARAMETER). An unconstrained caller, whose
|
||||
// mask is its group's whole active set, asks for no bound the child's own
|
||||
// group cannot give, so such a child keeps that group's default and the spawn
|
||||
// proceeds. A narrower mask is a deliberate CPU constraint that a child in
|
||||
// another group cannot express, and silently widening it would hand the
|
||||
// provider tree the whole group, so that spawn fails naming the constraint.
|
||||
DWORD_PTR affinity = 0, systemAffinity = 0;
|
||||
require(GetProcessAffinityMask(GetCurrentProcess(), &affinity, &systemAffinity),
|
||||
"Read caller process affinity failed", command);
|
||||
USHORT callerGroup = 0, childGroup = 0;
|
||||
const bool sharedGroup = singleProcessorGroup(GetCurrentProcess(), callerGroup) &&
|
||||
singleProcessorGroup(result->process.get(), childGroup) &&
|
||||
callerGroup == childGroup;
|
||||
if (affinity != 0 && sharedGroup)
|
||||
if (affinity != 0)
|
||||
require(SetProcessAffinityMask(result->process.get(), affinity), "Preserve caller process affinity failed", command);
|
||||
else
|
||||
require(affinity == 0 || affinity == systemAffinity,
|
||||
"Caller CPU affinity cannot bound an owned process in another processor group", command,
|
||||
ERROR_INVALID_PARAMETER);
|
||||
const DWORD priority = GetPriorityClass(GetCurrentProcess());
|
||||
require(priority != 0 && SetPriorityClass(result->process.get(), priority),
|
||||
"Preserve caller process priority failed", command);
|
||||
|
||||
@@ -45,20 +45,6 @@ class Generator:
|
||||
assert "ows-secret" not in json.dumps(projected), projected
|
||||
if isinstance(value, bytes):
|
||||
assert projected["binary_fields"][-1]["state"] == "redacted", projected
|
||||
body = b"A" * 12345
|
||||
state = {"response": {"content": body}}
|
||||
control = adapter.project_record(state, [])
|
||||
field = control["binary_fields"][0]
|
||||
assert field["state"] == "retained" and field["bytes"] == len(body), control
|
||||
for literal in ["12345", "2345"]:
|
||||
# Only the generated byte count matches this exclusion.
|
||||
assert literal not in control["reported"]["response"]["content"]
|
||||
assert literal not in field["content_base64"] and literal not in field["sha256"]
|
||||
projected = adapter.project_record(state, [literal])
|
||||
assert projected["reported"]["response"]["content"] is None, projected
|
||||
assert projected["binary_fields"] == [{"pointer": "/response/content", "representation": "producer-bytes", "state": "redacted", "content_base64": None, "bytes": None, "sha256": None}], projected
|
||||
assert {"pointer": "/response/content", "reason": "explicit-sensitive-value"} in projected["redactions"], projected
|
||||
assert literal not in json.dumps(projected), projected
|
||||
(root / "native-error-classifications.json").write_text(json.dumps({"passed": len(classifications) + 2}))
|
||||
first = http.HTTPFlow(connection.Client(peername=("127.0.0.1", 1), sockname=("127.0.0.1", 2)), connection.Server(address=("example.test", 80)))
|
||||
first.id = "original-producer-id"
|
||||
|
||||
@@ -662,42 +662,6 @@ setInterval(()=>{},1000);\n`,
|
||||
unicodeNamesPreserved: true,
|
||||
});
|
||||
report.processes.windowsEnvironmentSemantics = true;
|
||||
// Observed through this process's own id: a separate probe process would
|
||||
// get its own processor group, so it cannot stand in for the process that
|
||||
// spawns the child.
|
||||
const callerAffinity = JSON.parse(
|
||||
execFileSync(boundaryFixture, ["affinity", String(process.pid)], {
|
||||
encoding: "utf8",
|
||||
}),
|
||||
);
|
||||
const affinityChild = native.call("process_spawn", [
|
||||
boundaryFixture,
|
||||
`${quote(boundaryFixture)} affinity`,
|
||||
workspace,
|
||||
environment,
|
||||
]);
|
||||
const observedAffinity = await wait(affinityChild);
|
||||
native.call("process_close", [affinityChild.handle]);
|
||||
assert.equal(observedAffinity.exitCode, 0);
|
||||
const childAffinity = JSON.parse(observedAffinity.output);
|
||||
// Masks cross as hexadecimal strings because a mask can exceed the
|
||||
// safe-integer range. Sharing one processor group makes the caller's mask
|
||||
// applicable, so it must be inherited exactly. Windows placing the child in
|
||||
// another group is only permitted when the caller asked for no bound of its
|
||||
// own, which its group's whole active set establishes; a narrower mask has
|
||||
// to fail the spawn rather than widen to that group's default.
|
||||
const sharedGroup =
|
||||
callerAffinity.singleProcessorGroup &&
|
||||
childAffinity.singleProcessorGroup &&
|
||||
callerAffinity.processorGroup === childAffinity.processorGroup;
|
||||
if (sharedGroup)
|
||||
assert.equal(childAffinity.affinityMask, callerAffinity.affinityMask);
|
||||
else assert.equal(callerAffinity.affinityMask, callerAffinity.systemMask);
|
||||
report.processes.callerAffinityBoundsOwnedProcessOrRefusesToWiden = true;
|
||||
report.callerAffinity = {
|
||||
...callerAffinity,
|
||||
sharedGroupWithChild: sharedGroup,
|
||||
};
|
||||
}
|
||||
const ownerFixture = join(workspace, "owner.mjs");
|
||||
const ownerPidFile = join(workspace, "crash-child.pid");
|
||||
|
||||
@@ -2,16 +2,12 @@ import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
installMacHopper,
|
||||
type MacHopperBundleVerification,
|
||||
type MacHopperInstallHost,
|
||||
} from "./MacHopper.js";
|
||||
import { installMacHopper, type MacHopperInstallHost } from "./MacHopper.js";
|
||||
|
||||
class FakeMacHopperHost implements MacHopperInstallHost {
|
||||
readonly archive = new TextEncoder().encode("hopper-dmg");
|
||||
archiveOk = true;
|
||||
verification: MacHopperBundleVerification = "verified";
|
||||
valid = true;
|
||||
existing = false;
|
||||
mountSucceeds = true;
|
||||
copySucceeds = true;
|
||||
@@ -19,7 +15,6 @@ class FakeMacHopperHost implements MacHopperInstallHost {
|
||||
badHash = false;
|
||||
unmounts = 0;
|
||||
cleanups = 0;
|
||||
installs = 0;
|
||||
opens = 0;
|
||||
replaces = false;
|
||||
|
||||
@@ -52,7 +47,7 @@ class FakeMacHopperHost implements MacHopperInstallHost {
|
||||
return Promise.resolve();
|
||||
};
|
||||
appBundle = () => Promise.resolve("/mounted/Hopper Disassembler.app");
|
||||
validBundle = () => Promise.resolve(this.verification);
|
||||
validBundle = () => Promise.resolve(this.valid);
|
||||
destinationExists = () => Promise.resolve(this.existing);
|
||||
installBundle = (
|
||||
_source: string,
|
||||
@@ -60,7 +55,6 @@ class FakeMacHopperHost implements MacHopperInstallHost {
|
||||
_stage: string,
|
||||
replaceExisting: boolean,
|
||||
) => {
|
||||
this.installs += 1;
|
||||
this.replaces = replaceExisting;
|
||||
return Promise.resolve(this.copySucceeds);
|
||||
};
|
||||
@@ -121,7 +115,7 @@ describe("macOS Hopper installation", () => {
|
||||
|
||||
it("cleans and detaches after bundle validation fails", async () => {
|
||||
const host = new FakeMacHopperHost();
|
||||
host.verification = "invalid_signature";
|
||||
host.valid = false;
|
||||
await expect(installMacHopper({}, host)).resolves.toEqual({
|
||||
status: "failed",
|
||||
reason: "bundle",
|
||||
@@ -129,17 +123,4 @@ describe("macOS Hopper installation", () => {
|
||||
expect(host.unmounts).toBe(1);
|
||||
expect(host.cleanups).toBe(1);
|
||||
});
|
||||
|
||||
it("reports a publisher mismatch without copying or launching the bundle", async () => {
|
||||
const host = new FakeMacHopperHost();
|
||||
host.verification = "unverified_publisher";
|
||||
await expect(installMacHopper({}, host)).resolves.toEqual({
|
||||
status: "failed",
|
||||
reason: "publisher_verification_failed",
|
||||
});
|
||||
expect(host.installs).toBe(0);
|
||||
expect(host.opens).toBe(0);
|
||||
expect(host.unmounts).toBe(1);
|
||||
expect(host.cleanups).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -24,35 +24,7 @@ const execFileAsync = promisify(execFile);
|
||||
const RELEASES_URL =
|
||||
"https://www.hopperapp.com/include/files-api.php?request=releases&public=true";
|
||||
const DOWNLOAD_PREFIX = "https://www.hopperapp.com:443/downloader/public/";
|
||||
|
||||
/**
|
||||
* Apple publisher identity pinned for the official Hopper macOS bundle. The
|
||||
* team identifier was captured from `Hopper-6.6.0-demo.dmg` at
|
||||
* `https://www.hopperapp.com:443/downloader/public/Hopper-6.6.0-demo.dmg`
|
||||
* (34846271 bytes, SHA-1 0be530f038249742590992199c7b042ea20ca955) with
|
||||
* `codesign -dvvv`, which reported
|
||||
* `Authority=Developer ID Application: Cryptic Apps (2AMA2753NF)`.
|
||||
*/
|
||||
export const HOPPER_PUBLISHER = Object.freeze({
|
||||
bundleIdentifier: "com.cryptic-apps.hopper-web-4",
|
||||
teamIdentifier: "2AMA2753NF",
|
||||
});
|
||||
|
||||
/**
|
||||
* Code requirement enforcing the bundle identifier and signing team together.
|
||||
* The identifier is read from the sealed CodeDirectory, so it cannot be changed
|
||||
* by editing `Info.plist` the way the previous string comparison could.
|
||||
*/
|
||||
const HOPPER_PUBLISHER_REQUIREMENT =
|
||||
`= identifier "${HOPPER_PUBLISHER.bundleIdentifier}"` +
|
||||
` and anchor apple generic` +
|
||||
` and certificate leaf[subject.OU] = "${HOPPER_PUBLISHER.teamIdentifier}"`;
|
||||
|
||||
/** Outcome of reading a mounted bundle's signature and publisher identity. */
|
||||
export type MacHopperBundleVerification =
|
||||
| "verified"
|
||||
| "invalid_signature"
|
||||
| "unverified_publisher";
|
||||
const BUNDLE_IDENTIFIER = "com.cryptic-apps.hopper-web-4";
|
||||
|
||||
/** Stable network and command effects disclosed before macOS Hopper setup. */
|
||||
export const macHopperInstallDisclosure = {
|
||||
@@ -60,7 +32,6 @@ export const macHopperInstallDisclosure = {
|
||||
commands: [
|
||||
"hdiutil attach -readonly -nobrowse -mountpoint <private-mount> <verified-hopper.dmg>",
|
||||
"codesign --verify --deep --strict <mounted-hopper.app>",
|
||||
`codesign --verify --strict '-R${HOPPER_PUBLISHER_REQUIREMENT}' <mounted-hopper.app>`,
|
||||
"ditto <mounted-hopper.app> <user-Applications-stage>",
|
||||
"open <installed-hopper.app>",
|
||||
] as const,
|
||||
@@ -81,7 +52,6 @@ export type MacHopperInstallResult =
|
||||
| "integrity"
|
||||
| "mount"
|
||||
| "bundle"
|
||||
| "publisher_verification_failed"
|
||||
| "destination_exists"
|
||||
| "copy"
|
||||
| "launcher_missing";
|
||||
@@ -99,7 +69,7 @@ export interface MacHopperInstallHost {
|
||||
mount(packagePath: string, mountPath: string): Promise<boolean>;
|
||||
unmount(mountPath: string): Promise<void>;
|
||||
appBundle(mountPath: string): Promise<string | undefined>;
|
||||
validBundle(appPath: string): Promise<MacHopperBundleVerification>;
|
||||
validBundle(appPath: string): Promise<boolean>;
|
||||
destinationExists(path: string): Promise<boolean>;
|
||||
installBundle(
|
||||
source: string,
|
||||
@@ -154,12 +124,8 @@ export const installMacHopper = async (
|
||||
return { status: "failed", reason: "mount" };
|
||||
mounted = true;
|
||||
const source = await host.appBundle(mountPath);
|
||||
if (source === undefined) return { status: "failed", reason: "bundle" };
|
||||
const verification = await host.validBundle(source);
|
||||
if (verification === "invalid_signature")
|
||||
if (source === undefined || !(await host.validBundle(source)))
|
||||
return { status: "failed", reason: "bundle" };
|
||||
if (verification === "unverified_publisher")
|
||||
return { status: "failed", reason: "publisher_verification_failed" };
|
||||
const stage = `${destination}.rea-stage`;
|
||||
if (
|
||||
!(await host.installBundle(
|
||||
@@ -256,21 +222,25 @@ export const systemMacHopperInstallHost = (
|
||||
environment,
|
||||
))
|
||||
)
|
||||
return "invalid_signature";
|
||||
if (
|
||||
!(await commandSucceeds(
|
||||
"codesign",
|
||||
[
|
||||
"--verify",
|
||||
"--strict",
|
||||
`-R${HOPPER_PUBLISHER_REQUIREMENT}`,
|
||||
appPath,
|
||||
],
|
||||
environment,
|
||||
))
|
||||
)
|
||||
return "unverified_publisher";
|
||||
return "verified";
|
||||
return false;
|
||||
try {
|
||||
const identifier = (
|
||||
await execFileAsync(
|
||||
"/usr/libexec/PlistBuddy",
|
||||
[
|
||||
"-c",
|
||||
"Print :CFBundleIdentifier",
|
||||
join(appPath, "Contents/Info.plist"),
|
||||
],
|
||||
{ env: environment },
|
||||
)
|
||||
).stdout.trim();
|
||||
return identifier === BUNDLE_IDENTIFIER;
|
||||
} catch (cause: unknown) {
|
||||
// best-effort cleanup: optional bundle probing; unreadable means invalid.
|
||||
void cause;
|
||||
return false;
|
||||
}
|
||||
},
|
||||
async destinationExists(path) {
|
||||
try {
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { HOPPER_PUBLISHER } from "./MacHopper.js";
|
||||
import { setupInstallFailure } from "./SetupInstallFailure.js";
|
||||
|
||||
describe("macOS Hopper setup failure projection", () => {
|
||||
it("projects a publisher mismatch onto its own code and recovery", () => {
|
||||
expect(setupInstallFailure("publisher_verification_failed")).toEqual({
|
||||
status: "failed",
|
||||
code: "publisher_verification_failed",
|
||||
remediation: `The mounted Hopper application is not signed by the publisher REA pins (${HOPPER_PUBLISHER.bundleIdentifier}, Apple team ${HOPPER_PUBLISHER.teamIdentifier}); nothing was copied or launched. Install Hopper yourself and set HOPPER_LAUNCHER_PATH to its launcher, then rerun rea setup.`,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a broken bundle distinct from a publisher mismatch", () => {
|
||||
expect(setupInstallFailure("bundle")).toEqual({
|
||||
status: "failed",
|
||||
code: "bundle_invalid",
|
||||
remediation:
|
||||
"The mounted package did not contain the expected Hopper application bundle. Retry setup; if it repeats, update REA before installing.",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,3 @@
|
||||
import { HOPPER_PUBLISHER } from "./MacHopper.js";
|
||||
|
||||
export type SetupFailureCode =
|
||||
| "unsupported_host"
|
||||
| "download_failed"
|
||||
@@ -12,7 +10,6 @@ export type SetupFailureCode =
|
||||
| "destination_exists"
|
||||
| "mount_failed"
|
||||
| "bundle_invalid"
|
||||
| "publisher_verification_failed"
|
||||
| "copy_failed"
|
||||
| "skill_install_failed"
|
||||
| "cleanup_failed";
|
||||
@@ -42,7 +39,6 @@ export type HopperInstallFailureReason =
|
||||
| "destination_exists"
|
||||
| "mount"
|
||||
| "bundle"
|
||||
| "publisher_verification_failed"
|
||||
| "copy";
|
||||
|
||||
/** Map provider installer failures to stable setup codes and safe recovery. */
|
||||
@@ -119,12 +115,6 @@ export const setupInstallFailure = (
|
||||
remediation:
|
||||
"The mounted package did not contain the expected Hopper application bundle. Retry setup; if it repeats, update REA before installing.",
|
||||
};
|
||||
case "publisher_verification_failed":
|
||||
return {
|
||||
status: "failed",
|
||||
code: "publisher_verification_failed",
|
||||
remediation: `The mounted Hopper application is not signed by the publisher REA pins (${HOPPER_PUBLISHER.bundleIdentifier}, Apple team ${HOPPER_PUBLISHER.teamIdentifier}); nothing was copied or launched. Install Hopper yourself and set HOPPER_LAUNCHER_PATH to its launcher, then rerun rea setup.`,
|
||||
};
|
||||
case "copy":
|
||||
return {
|
||||
status: "failed",
|
||||
|
||||
@@ -17,7 +17,6 @@ import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
|
||||
import { SafeOutputTree } from "../SafeOutputTree.js";
|
||||
import { SafeOutputTreeCreationFailure } from "../SafeOutputTreeCreationFailure.js";
|
||||
import { ZipArtifactReader } from "../ZipArtifactReader.js";
|
||||
import { isZipPackageFormat } from "../../domain/zipPackageFormat.js";
|
||||
import { MachOSliceArtifactReader } from "../MachOSliceArtifactReader.js";
|
||||
import {
|
||||
artifactExtractionResultSchema,
|
||||
@@ -401,6 +400,13 @@ interface ExtractionInventory {
|
||||
readonly integrityContradictions: readonly IntegrityContradiction[];
|
||||
}
|
||||
|
||||
const ZIP_FORMATS = ["ipa", "apk", "msix", "appx", "zip"] as const;
|
||||
|
||||
const isZipFormat = (
|
||||
format: BinaryTarget["format"],
|
||||
): format is (typeof ZIP_FORMATS)[number] =>
|
||||
(ZIP_FORMATS as readonly string[]).includes(format);
|
||||
|
||||
/**
|
||||
* Refuse a format without an extraction reader before inventory work starts.
|
||||
* The target kind, not the host, is unsupported by extraction. The error keeps
|
||||
@@ -416,7 +422,7 @@ const requireExtractableFormat = async (
|
||||
!directory &&
|
||||
format !== "asar" &&
|
||||
!isMachOFormat(format) &&
|
||||
!isZipPackageFormat(format)
|
||||
!isZipFormat(format)
|
||||
)
|
||||
throw new AnalysisUnsupportedTargetError(
|
||||
"extract_artifact",
|
||||
@@ -437,7 +443,7 @@ const createReader = async (
|
||||
if (await requireExtractableFormat(path, input))
|
||||
return new DirectoryArtifactReader(path);
|
||||
if (format === "asar") return new AsarArtifactReader(path);
|
||||
if (isZipPackageFormat(format)) return new ZipArtifactReader(path, format);
|
||||
if (isZipFormat(format)) return new ZipArtifactReader(path, format);
|
||||
return new MachOSliceArtifactReader(path, input.environment);
|
||||
};
|
||||
|
||||
|
||||
@@ -144,8 +144,7 @@ const projectHar = (
|
||||
(literal) =>
|
||||
item.includes(literal) ||
|
||||
contentBase64.includes(literal) ||
|
||||
sha256.includes(literal) ||
|
||||
String(bytes.length).includes(literal),
|
||||
sha256.includes(literal),
|
||||
);
|
||||
binary_fields.push(
|
||||
hidden
|
||||
|
||||
@@ -597,136 +597,6 @@ describe("dyld load order", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("loader-relative dylib resolution", () => {
|
||||
it("does not reuse already loaded images by install name for @loader_path dependencies", async () => {
|
||||
const pluginA = "Contents/PlugIns/A/pluginA.dylib";
|
||||
const helperA = "Contents/PlugIns/A/libhelper.dylib";
|
||||
const pluginB = "Contents/PlugIns/B/pluginB.dylib";
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({
|
||||
[MAIN]: executable({
|
||||
dependencies: [
|
||||
dependency("@executable_path/../PlugIns/A/pluginA.dylib"),
|
||||
dependency("@executable_path/../PlugIns/B/pluginB.dylib"),
|
||||
],
|
||||
}),
|
||||
[pluginA]: parsed(
|
||||
slice({
|
||||
dependencies: [dependency("@loader_path/libhelper.dylib")],
|
||||
}),
|
||||
),
|
||||
[helperA]: parsed(
|
||||
slice({
|
||||
install_name: "@loader_path/libhelper.dylib",
|
||||
}),
|
||||
),
|
||||
[pluginB]: parsed(
|
||||
slice({
|
||||
dependencies: [dependency("@loader_path/libhelper.dylib")],
|
||||
}),
|
||||
),
|
||||
}),
|
||||
{ roots: [MAIN] },
|
||||
);
|
||||
|
||||
const edgeA = edgeFor(trace, pluginA, "@loader_path/libhelper.dylib");
|
||||
expect(edgeA.resolution).toEqual({
|
||||
status: "resolved",
|
||||
image: helperA,
|
||||
});
|
||||
expect(edgeA.candidates).toEqual([
|
||||
expect.objectContaining({
|
||||
source: "loader_path",
|
||||
outcome: "resolved",
|
||||
resolved_path: helperA,
|
||||
}),
|
||||
]);
|
||||
|
||||
const edgeB = edgeFor(trace, pluginB, "@loader_path/libhelper.dylib");
|
||||
expect(edgeB.resolution).toEqual({
|
||||
status: "unresolved",
|
||||
image: null,
|
||||
});
|
||||
expect(edgeB.candidates).toEqual([
|
||||
expect.objectContaining({
|
||||
path: "Contents/PlugIns/B/libhelper.dylib",
|
||||
source: "loader_path",
|
||||
outcome: "absent",
|
||||
resolved_path: null,
|
||||
}),
|
||||
]);
|
||||
expect(trace.findings).toContainEqual(
|
||||
expect.objectContaining({
|
||||
kind: "required-load-unresolved",
|
||||
image: pluginB,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("resolves @loader_path dependencies to the loader's own directory when multiple helpers exist", async () => {
|
||||
const pluginA = "Contents/PlugIns/A/pluginA.dylib";
|
||||
const helperA = "Contents/PlugIns/A/libhelper.dylib";
|
||||
const pluginB = "Contents/PlugIns/B/pluginB.dylib";
|
||||
const helperB = "Contents/PlugIns/B/libhelper.dylib";
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({
|
||||
[MAIN]: executable({
|
||||
dependencies: [
|
||||
dependency("@executable_path/../PlugIns/A/pluginA.dylib"),
|
||||
dependency("@executable_path/../PlugIns/B/pluginB.dylib"),
|
||||
],
|
||||
}),
|
||||
[pluginA]: parsed(
|
||||
slice({
|
||||
dependencies: [dependency("@loader_path/libhelper.dylib")],
|
||||
}),
|
||||
),
|
||||
[helperA]: parsed(
|
||||
slice({
|
||||
install_name: "@loader_path/libhelper.dylib",
|
||||
}),
|
||||
),
|
||||
[pluginB]: parsed(
|
||||
slice({
|
||||
dependencies: [dependency("@loader_path/libhelper.dylib")],
|
||||
}),
|
||||
),
|
||||
[helperB]: parsed(
|
||||
slice({
|
||||
install_name: "@loader_path/libhelper.dylib",
|
||||
}),
|
||||
),
|
||||
}),
|
||||
{ roots: [MAIN] },
|
||||
);
|
||||
|
||||
expect(
|
||||
edgeFor(trace, pluginA, "@loader_path/libhelper.dylib"),
|
||||
).toMatchObject({
|
||||
resolution: { status: "resolved", image: helperA },
|
||||
candidates: [
|
||||
expect.objectContaining({
|
||||
source: "loader_path",
|
||||
outcome: "resolved",
|
||||
resolved_path: helperA,
|
||||
}),
|
||||
],
|
||||
});
|
||||
expect(
|
||||
edgeFor(trace, pluginB, "@loader_path/libhelper.dylib"),
|
||||
).toMatchObject({
|
||||
resolution: { status: "resolved", image: helperB },
|
||||
candidates: [
|
||||
expect.objectContaining({
|
||||
source: "loader_path",
|
||||
outcome: "resolved",
|
||||
resolved_path: helperB,
|
||||
}),
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("dyld slice compatibility and coverage", () => {
|
||||
it("lets an x86_64h process load generic x86_64 but not arm64e load arm64", async () => {
|
||||
const files = {
|
||||
|
||||
@@ -427,9 +427,7 @@ const resolveDependency = async (
|
||||
): Promise<Edge> => {
|
||||
const current = context.loaded.get(loader);
|
||||
const chain = current?.chain ?? [loader];
|
||||
const loaded = dependency.install_name.startsWith("@rpath/")
|
||||
? context.byInstallName.get(dependency.install_name)
|
||||
: undefined;
|
||||
const loaded = context.byInstallName.get(dependency.install_name);
|
||||
const candidates: Candidate[] = [];
|
||||
if (loaded !== undefined)
|
||||
candidates.push({
|
||||
@@ -508,10 +506,7 @@ const traceProcess = async (
|
||||
chain: [context.root],
|
||||
conditional: false,
|
||||
});
|
||||
if (
|
||||
rootSlice.install_name !== null &&
|
||||
rootSlice.install_name.startsWith("@rpath/")
|
||||
)
|
||||
if (rootSlice.install_name !== null)
|
||||
context.byInstallName.set(rootSlice.install_name, context.root);
|
||||
const pending = [context.root];
|
||||
while (pending.length > 0) {
|
||||
@@ -542,7 +537,6 @@ const traceProcess = async (
|
||||
});
|
||||
if (
|
||||
slice.install_name !== null &&
|
||||
slice.install_name.startsWith("@rpath/") &&
|
||||
!context.byInstallName.has(slice.install_name)
|
||||
)
|
||||
context.byInstallName.set(slice.install_name, image);
|
||||
|
||||
@@ -91,7 +91,7 @@ export const DYLIB_RESOLUTION_LIMITATIONS = [
|
||||
"Slices are matched by dyld's graded architectures (an x86_64h process also loads x86_64). arm64e processes that disable pointer authentication can also load arm64 slices; that fallback is not modeled.",
|
||||
"Absolute install names and rpaths are outside the analyzed root and are not evaluated, including /System and /usr/lib libraries that the dyld shared cache usually provides.",
|
||||
"Leaf and relative install names depend on dyld fallback paths, DYLD_* variables, and the working directory; they are undetermined.",
|
||||
"Load order follows dyld's dependents-first traversal in load-command order. An image reached through several chains is resolved once per process, with the rpath stack and conditionality of the first chain; a later @rpath request whose install name matches an already loaded image reuses it.",
|
||||
"Load order follows dyld's dependents-first traversal in load-command order. An image reached through several chains is resolved once per process, with the rpath stack and conditionality of the first chain; a later request whose install name matches an already loaded image reuses it.",
|
||||
"@loader_path uses each image's symlink-resolved path within the analyzed root.",
|
||||
"Code-signing checks that can reject a found image, such as library validation and the hardened runtime, are not evaluated.",
|
||||
"Dylib compatibility versions are not compared. Apple's linker documentation describes a load-time rejection when an image's compatibility version is older than the loader requires, but dyld on macOS 26 was observed to load such an image.",
|
||||
|
||||
@@ -116,24 +116,6 @@ it("keeps unsupported profile reasons distinct from malformed input", () => {
|
||||
expect(JSON.stringify(projectAnalysisError(result))).not.toContain("private");
|
||||
});
|
||||
|
||||
it("preserves a retryable capability failure through explicit-value redaction", () => {
|
||||
// Retryability is a semantic field of the error, not presentation: dropping
|
||||
// it turns a transient admission failure into a permanent one and changes
|
||||
// the remediation the caller is shown.
|
||||
const error = new AnalysisCapabilityUnavailableError(
|
||||
"mitmproxy",
|
||||
"inspect_web_network_capture",
|
||||
"Runtime admission for /targets/private/capture failed transiently",
|
||||
{ retryable: true },
|
||||
);
|
||||
expect(projectAnalysisError(error).retryable).toBe(true);
|
||||
const result = redactExplicitFailure(error, ["private"]);
|
||||
expect(result).toBeInstanceOf(AnalysisCapabilityUnavailableError);
|
||||
expect((result as AnalysisCapabilityUnavailableError).retryable).toBe(true);
|
||||
expect(projectAnalysisError(result).retryable).toBe(true);
|
||||
expect(JSON.stringify(projectAnalysisError(result))).not.toContain("private");
|
||||
});
|
||||
|
||||
it("coarsens format issue pointers without creating replacement coordinates", () => {
|
||||
const error = new AnalysisInputError(
|
||||
"inspect_web_network_capture",
|
||||
|
||||
@@ -154,7 +154,6 @@ export const redactExplicitFailure = (
|
||||
...(error.userMessage === undefined
|
||||
? {}
|
||||
: { userMessage: text(error.userMessage) }),
|
||||
...(error.retryable ? { retryable: true } : {}),
|
||||
},
|
||||
);
|
||||
if (error instanceof AnalysisResourceConstraintError)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { posix, win32 } from "node:path";
|
||||
import { posix, relative, win32 } from "node:path";
|
||||
|
||||
import type { ApplicationNode } from "./javascriptApplicationGraphSchemas.js";
|
||||
import type { JavaScriptApplicationGraph } from "./javascriptApplicationGraph.js";
|
||||
@@ -216,7 +216,7 @@ const pathBelowRoot = (root: string, value: string): string | null => {
|
||||
const remainder =
|
||||
rootStyle === "windows"
|
||||
? win32.relative(root, value)
|
||||
: posix.relative(root, value);
|
||||
: relative(root, value);
|
||||
const portableRemainder = remainder.replaceAll("\\", "/");
|
||||
if (
|
||||
remainder === "" ||
|
||||
|
||||
@@ -33,24 +33,3 @@ it("rejects incomplete headers, invalid signatures and zero dimensions", () => {
|
||||
expect(readPngHeaderDimensions(zero)).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([0, 12, 14, 0xffff_ffff])("rejects IHDR data length %s", (length) => {
|
||||
const bytes = Buffer.from(png);
|
||||
bytes.writeUInt32BE(length, 8);
|
||||
expect(readPngHeaderDimensions(bytes)).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each([16, 20])("rejects out-of-range PNG dimension at %s", (offset) => {
|
||||
const bytes = Buffer.from(png);
|
||||
bytes.writeUInt32BE(0x8000_0000, offset);
|
||||
expect(readPngHeaderDimensions(bytes)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("accepts the largest dimension representable by the PNG specification", () => {
|
||||
const bytes = Buffer.from(png);
|
||||
bytes.writeUInt32BE(0x7fff_ffff, 16);
|
||||
expect(readPngHeaderDimensions(bytes)).toEqual({
|
||||
width: 0x7fff_ffff,
|
||||
height: 1,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,16 +8,10 @@ export const readPngHeaderDimensions = (
|
||||
if (
|
||||
bytes.byteLength < 24 ||
|
||||
!bytes.subarray(0, 8).equals(PNG_SIGNATURE) ||
|
||||
bytes.readUInt32BE(8) !== 13 ||
|
||||
!bytes.subarray(12, 16).equals(IHDR_TYPE)
|
||||
)
|
||||
return undefined;
|
||||
const width = bytes.readUInt32BE(16);
|
||||
const height = bytes.readUInt32BE(20);
|
||||
return width === 0 ||
|
||||
height === 0 ||
|
||||
width > 0x7fff_ffff ||
|
||||
height > 0x7fff_ffff
|
||||
? undefined
|
||||
: { width, height };
|
||||
return width === 0 || height === 0 ? undefined : { width, height };
|
||||
};
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { parseProcessCapture } from "./processCaptureParsing.js";
|
||||
import type { ProcessTraceSpecification } from "./processTraceSpecification.js";
|
||||
import { processTraceSpecificationSchema as specificationSchema } from "./processTraceSpecification.js";
|
||||
import { processTraceComparisonResultSchema } from "./processTraceEvaluation.js";
|
||||
import {
|
||||
capture,
|
||||
@@ -101,33 +100,6 @@ describe("generic capture trace comparison", () => {
|
||||
right: { matched_variant: "two" },
|
||||
});
|
||||
});
|
||||
|
||||
it("compares a declared identifier the comparison result can represent", () => {
|
||||
// The specification owns the trace identifier vocabulary and the result
|
||||
// echoes those identifiers verbatim, so both must accept the same values
|
||||
// rather than handing the caller a raw schema error for its own input.
|
||||
const eventId = `e${"0".repeat(64)}`;
|
||||
const specification: ProcessTraceSpecification = {
|
||||
events: [
|
||||
{
|
||||
id: eventId,
|
||||
source: "terminal_raw",
|
||||
exact: terminal,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
],
|
||||
language: {
|
||||
kind: "finite_traces",
|
||||
variants: [{ id: "only", trace: [eventId] }],
|
||||
},
|
||||
};
|
||||
expect(specificationSchema.safeParse(specification).success).toBe(true);
|
||||
const left = capture(values(["terminal", "process"]));
|
||||
expect(compareProcessTraces(left, left, specification)).toMatchObject({
|
||||
verdict: "equivalent",
|
||||
left: { matched_variant: "only", raw_trace: [{ event_id: eventId }] },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("process trace constraints and evidence sufficiency", () => {
|
||||
|
||||
@@ -13,12 +13,13 @@ import {
|
||||
import {
|
||||
canonicalTraceJson,
|
||||
processTraceCardinalityBounds,
|
||||
processTraceIdentifierSchema,
|
||||
type ProcessTraceSpecification,
|
||||
} from "./processTraceSpecification.js";
|
||||
|
||||
const identifierSchema = z.string().regex(/^[A-Za-z][A-Za-z0-9._\x2d]{0,63}$/u);
|
||||
|
||||
const matchedEventSchema = z.strictObject({
|
||||
event_id: processTraceIdentifierSchema,
|
||||
event_id: identifierSchema,
|
||||
location: processObservationLocationSchema,
|
||||
});
|
||||
|
||||
@@ -31,7 +32,7 @@ const sideResultSchema = z.union([
|
||||
z.strictObject({
|
||||
...sideResultShape,
|
||||
status: z.literal("pass"),
|
||||
matched_variant: processTraceIdentifierSchema.nullable(),
|
||||
matched_variant: identifierSchema.nullable(),
|
||||
}),
|
||||
z.strictObject({
|
||||
...sideResultShape,
|
||||
@@ -52,7 +53,7 @@ const diagnosticSchema = z.strictObject({
|
||||
]),
|
||||
side: z.enum(["left", "right"]),
|
||||
message: z.string(),
|
||||
event_ids: z.array(processTraceIdentifierSchema),
|
||||
event_ids: z.array(identifierSchema),
|
||||
locations: z.array(processObservationLocationSchema),
|
||||
});
|
||||
|
||||
|
||||
@@ -9,16 +9,7 @@ import {
|
||||
processObservationSourceSchema,
|
||||
} from "./processObservation.js";
|
||||
|
||||
/**
|
||||
* A declared trace, event or variant identifier. The specification owns this
|
||||
* vocabulary and the comparison result echoes those identifiers verbatim, so
|
||||
* the result module must reuse this schema rather than restate the pattern:
|
||||
* two bounds on the same identifier would reject the result of an accepted
|
||||
* specification.
|
||||
*/
|
||||
export const processTraceIdentifierSchema = z
|
||||
.string()
|
||||
.regex(IDENTIFIER_PATTERN);
|
||||
const identifierSchema = z.string().regex(IDENTIFIER_PATTERN);
|
||||
|
||||
const cardinalitySchema = z.discriminatedUnion("kind", [
|
||||
z.strictObject({ kind: z.literal("required") }),
|
||||
@@ -40,7 +31,7 @@ const cardinalitySchema = z.discriminatedUnion("kind", [
|
||||
]);
|
||||
|
||||
const eventDeclarationSchema = z.strictObject({
|
||||
id: processTraceIdentifierSchema,
|
||||
id: identifierSchema,
|
||||
source: processObservationSourceSchema,
|
||||
exact: jsonValueSchema,
|
||||
ignore_fields: z
|
||||
@@ -65,31 +56,29 @@ const partialOrderLanguageSchema = z.strictObject({
|
||||
happens_before: z
|
||||
.array(
|
||||
z.strictObject({
|
||||
before: processTraceIdentifierSchema,
|
||||
after: processTraceIdentifierSchema,
|
||||
before: identifierSchema,
|
||||
after: identifierSchema,
|
||||
}),
|
||||
)
|
||||
.default([]),
|
||||
not_before: z
|
||||
.array(
|
||||
z.strictObject({
|
||||
event: processTraceIdentifierSchema,
|
||||
anchor: processTraceIdentifierSchema,
|
||||
event: identifierSchema,
|
||||
anchor: identifierSchema,
|
||||
}),
|
||||
)
|
||||
.default([]),
|
||||
unordered_groups: z
|
||||
.array(
|
||||
z.strictObject({ events: z.array(processTraceIdentifierSchema).min(2) }),
|
||||
)
|
||||
.array(z.strictObject({ events: z.array(identifierSchema).min(2) }))
|
||||
.default([]),
|
||||
prefix: z.array(processTraceIdentifierSchema).default([]),
|
||||
suffix: z.array(processTraceIdentifierSchema).default([]),
|
||||
prefix: z.array(identifierSchema).default([]),
|
||||
suffix: z.array(identifierSchema).default([]),
|
||||
});
|
||||
|
||||
const finiteTraceTokenSchema = z.union([
|
||||
processTraceIdentifierSchema,
|
||||
z.strictObject({ unordered: z.array(processTraceIdentifierSchema).min(2) }),
|
||||
identifierSchema,
|
||||
z.strictObject({ unordered: z.array(identifierSchema).min(2) }),
|
||||
]);
|
||||
|
||||
const finiteTraceLanguageSchema = z.strictObject({
|
||||
@@ -97,7 +86,7 @@ const finiteTraceLanguageSchema = z.strictObject({
|
||||
variants: z
|
||||
.array(
|
||||
z.strictObject({
|
||||
id: processTraceIdentifierSchema,
|
||||
id: identifierSchema,
|
||||
trace: z.array(finiteTraceTokenSchema),
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -23,7 +23,6 @@ import {
|
||||
AnalysisUnsupportedTargetError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { AnalysisProtocolError } from "../domain/analysisErrorCore.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
@@ -760,7 +759,7 @@ export class FlutterBuildProvider {
|
||||
toolchain_capped: value.libflutter.toolchainCapped,
|
||||
},
|
||||
}))
|
||||
.sort((left, right) => compareUnicodeCodePoints(left.abi, right.abi));
|
||||
.sort((left, right) => left.abi.localeCompare(right.abi));
|
||||
const flutterDetected = abis.some((entry) => entry.libapp.present);
|
||||
const partial =
|
||||
abis.some(
|
||||
@@ -872,7 +871,7 @@ export class FlutterBuildProvider {
|
||||
(left, right) =>
|
||||
(preference.indexOf(left.abi) + 1 || preference.length + 1) -
|
||||
(preference.indexOf(right.abi) + 1 || preference.length + 1) ||
|
||||
compareUnicodeCodePoints(left.abi, right.abi),
|
||||
left.abi.localeCompare(right.abi),
|
||||
)[0]!
|
||||
: candidates.find((candidate) => candidate.abi === abi);
|
||||
if (selected === undefined)
|
||||
|
||||
@@ -85,10 +85,8 @@ export class IdaWorkspace {
|
||||
slice === undefined
|
||||
? position + bytes.length
|
||||
: Math.min(position + bytes.length, slice.offset + slice.size);
|
||||
// A chunk after the slice has end < position, and a negative subarray
|
||||
// bound would count from the chunk's end instead of being empty.
|
||||
if (end > start) {
|
||||
const admitted = bytes.subarray(start - position, end - position);
|
||||
const admitted = bytes.subarray(start - position, end - position);
|
||||
if (admitted.length > 0) {
|
||||
inputHash.update(admitted);
|
||||
await input.write(admitted);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { parseBinaryTarget } from "../application/BinaryTargetResolver.js";
|
||||
import { parseExecutableHeader } from "../domain/binaryTarget.js";
|
||||
import { fat, thinMach } from "../domain/binaryTarget.fixture.js";
|
||||
import { fat } from "../domain/binaryTarget.fixture.js";
|
||||
import {
|
||||
createIdaTarget,
|
||||
RecordingIdaMcp,
|
||||
@@ -35,45 +35,6 @@ const universalTarget = async (hostArchitecture: "arm64" | "x64") => {
|
||||
return { bytes, target: resolved.value };
|
||||
};
|
||||
|
||||
/** One slice of a synthetic universal file: CPU type, offset and size. */
|
||||
interface Layout {
|
||||
readonly cpu: number;
|
||||
readonly offset: number;
|
||||
readonly size: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write a universal file whose slices span more than one 64 KiB read, each
|
||||
* filled with its own byte so bytes outside the selected slice are visible.
|
||||
*/
|
||||
const largeUniversalTarget = async (
|
||||
layout: readonly Layout[],
|
||||
hostArchitecture: "arm64" | "x64",
|
||||
) => {
|
||||
const directory = await createTestTempDirectory("rea-ida-thin-large-");
|
||||
roots.push(directory);
|
||||
const path = join(directory, "universal");
|
||||
const total = Math.max(...layout.map(({ offset, size }) => offset + size));
|
||||
const bytes = Buffer.alloc(total);
|
||||
bytes.writeUInt32BE(0xcafebabe, 0);
|
||||
bytes.writeUInt32BE(layout.length, 4);
|
||||
layout.forEach(({ cpu, offset, size }, index) => {
|
||||
const entry = 8 + index * 20;
|
||||
bytes.writeUInt32BE(cpu, entry);
|
||||
bytes.writeUInt32BE(offset, entry + 8);
|
||||
bytes.writeUInt32BE(size, entry + 12);
|
||||
bytes.writeUInt32BE(14, entry + 16);
|
||||
bytes.fill(0x11 * (index + 1), offset, offset + size);
|
||||
thinMach(0xfeedfacf, cpu).copy(bytes, offset);
|
||||
});
|
||||
await writeFile(path, bytes);
|
||||
const resolved = await parseBinaryTarget(path, { hostArchitecture });
|
||||
if (!resolved.ok) throw resolved.error;
|
||||
if (resolved.value.format !== "mach-o-universal")
|
||||
throw new Error("the universal fixture did not resolve as a FAT container");
|
||||
return { bytes, target: resolved.value };
|
||||
};
|
||||
|
||||
describe("IDA workspace input thinning", () => {
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"thins the selected arm64 slice into the private headless input",
|
||||
@@ -117,58 +78,6 @@ describe("IDA workspace input thinning", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"copies exactly the selected slice when later slices follow it across read boundaries",
|
||||
async () => {
|
||||
const { bytes, target } = await largeUniversalTarget(
|
||||
[
|
||||
{ cpu: 0x01000007, offset: 4096, size: 8480 },
|
||||
{ cpu: 0x0100000c, offset: 16384, size: 33464 },
|
||||
{ cpu: 0x00000007, offset: 65536, size: 33464 },
|
||||
],
|
||||
"arm64",
|
||||
);
|
||||
const workspace = await IdaWorkspace.allocate(target);
|
||||
roots.push(workspace.directory);
|
||||
await workspace.copyInput();
|
||||
|
||||
const input = await readFile(workspace.inputPath);
|
||||
const { offset, size } = target.universalSlice;
|
||||
expect(size, "the arm64 slice is selected").toBe(33464);
|
||||
expect(input.length, "no byte after the slice is copied").toBe(size);
|
||||
expect(input.equals(bytes.subarray(offset, offset + size))).toBe(true);
|
||||
expect(workspace.inputSha256).toBe(
|
||||
createHash("sha256")
|
||||
.update(bytes.subarray(offset, offset + size))
|
||||
.digest("hex"),
|
||||
);
|
||||
await workspace.remove();
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"copies exactly the first slice when it is selected and others follow",
|
||||
async () => {
|
||||
const { bytes, target } = await largeUniversalTarget(
|
||||
[
|
||||
{ cpu: 0x01000007, offset: 16384, size: 37456 },
|
||||
{ cpu: 0x0100000c, offset: 65536, size: 33464 },
|
||||
],
|
||||
"x64",
|
||||
);
|
||||
const workspace = await IdaWorkspace.allocate(target);
|
||||
roots.push(workspace.directory);
|
||||
await workspace.copyInput();
|
||||
|
||||
const input = await readFile(workspace.inputPath);
|
||||
const { offset, size } = target.universalSlice;
|
||||
expect(size, "the x86_64 slice is selected").toBe(37456);
|
||||
expect(input.length, "no byte after the slice is copied").toBe(size);
|
||||
expect(input.equals(bytes.subarray(offset, offset + size))).toBe(true);
|
||||
await workspace.remove();
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps a whole-file copy for thin targets", async () => {
|
||||
const { root, target } = await createIdaTarget("arm64");
|
||||
roots.push(root);
|
||||
|
||||
@@ -35,37 +35,6 @@ const validPng = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jv4sAAAAASUVORK5CYII=",
|
||||
"base64",
|
||||
);
|
||||
it.each([
|
||||
{ offset: 8, value: 12 },
|
||||
{ offset: 16, value: 0x8000_0000 },
|
||||
{ offset: 20, value: 0x8000_0000 },
|
||||
])(
|
||||
"rejects invalid IHDR metadata with a matching digest",
|
||||
async ({ offset, value }) => {
|
||||
const bytes = Buffer.from(validPng);
|
||||
bytes.writeUInt32BE(value, offset);
|
||||
const screenshot = {
|
||||
mime_type: "image/png",
|
||||
base64: bytes.toString("base64"),
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
width: bytes.readUInt32BE(16),
|
||||
height: bytes.readUInt32BE(20),
|
||||
};
|
||||
const result = await observeNativeUi(
|
||||
target,
|
||||
"observe_native_ui",
|
||||
{ ...scope, screenshot: true },
|
||||
{
|
||||
environment: {},
|
||||
invoke: async () => ({
|
||||
ok: true,
|
||||
result: { ...snapshot, screenshot },
|
||||
}),
|
||||
},
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
},
|
||||
);
|
||||
describe("native UI screenshot validation", () => {
|
||||
it("rejects malformed or mismatched screenshot bytes from the helper", async () => {
|
||||
const screenshot = {
|
||||
|
||||
@@ -83,24 +83,6 @@ it("counts IPv6 endpoints once per packet and preserves every examined fact", as
|
||||
expect(result.partial).toBe(false);
|
||||
});
|
||||
|
||||
it("orders equal-count endpoints and protocols by code point, not host locale", async () => {
|
||||
// Locale collation puts "fe80::1" first and, under da-DK, "aarp" after "zz".
|
||||
const result = await parseTsharkJsonOutput(
|
||||
capture([
|
||||
{ "ipv6.src": ["fe80::1"], "frame.protocols": ["eth:llc:zz"] },
|
||||
{ "ipv6.src": ["fe80:1::1"], "frame.protocols": ["eth:llc:aarp"] },
|
||||
]),
|
||||
);
|
||||
expect(result.endpoints.map(({ address }) => address)).toEqual([
|
||||
"fe80:1::1",
|
||||
"fe80::1",
|
||||
]);
|
||||
expect(result.protocolDistribution.map(({ protocol }) => protocol)).toEqual([
|
||||
"eth:llc:aarp",
|
||||
"eth:llc:zz",
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves all DNS addresses and their exact examined count", async () => {
|
||||
const result = await parseTsharkJsonOutput(
|
||||
capture(
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
AnalysisResourceConstraintError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { parseRecordedTransportUrl } from "../domain/recordedTransportUrl.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
|
||||
const OPERATION = "inspect_pcap_capture";
|
||||
/** Bounds JSON decoding plus its expanded object graph before JSON.parse. */
|
||||
@@ -285,7 +284,7 @@ export const parseTsharkJsonOutput = async (
|
||||
signal?.throwIfAborted();
|
||||
return {
|
||||
endpoints: [...endpoints]
|
||||
.sort((a, b) => b[1] - a[1] || compareUnicodeCodePoints(a[0], b[0]))
|
||||
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
|
||||
.map(([address, packet_count]) => ({
|
||||
address,
|
||||
port: null,
|
||||
@@ -301,7 +300,7 @@ export const parseTsharkJsonOutput = async (
|
||||
tlsSniValues: [...sni],
|
||||
tlsSniCount: sni.size,
|
||||
protocolDistribution: [...protocols]
|
||||
.sort((a, b) => b[1] - a[1] || compareUnicodeCodePoints(a[0], b[0]))
|
||||
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
|
||||
.map(([protocol, packet_count]) => ({ protocol, packet_count })),
|
||||
protocolCount: protocols.size,
|
||||
httpRequestUris: [...uris],
|
||||
|
||||
@@ -12,8 +12,6 @@ import { err, ok } from "../domain/result.js";
|
||||
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
|
||||
import { inspectEvidenceBundle } from "../application/investigation/InspectEvidenceBundle.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import { withAdmittedAnalysis } from "./analysisAdmission.js";
|
||||
import { runAdmittedToolOperation } from "./admittedToolOperation.js";
|
||||
|
||||
interface EvidenceToolRegistration {
|
||||
readonly server: EvidenceMcpServer;
|
||||
@@ -94,54 +92,40 @@ const registerImportEvidenceTool = ({
|
||||
resources,
|
||||
importContract,
|
||||
}: EvidenceToolRegistration): void => {
|
||||
const admission = withAdmittedAnalysis({ kind: "session", session });
|
||||
server.registerTool(
|
||||
importContract.name,
|
||||
toolRegistrationOptions(importContract),
|
||||
async (input, context) =>
|
||||
runAdmittedToolOperation(
|
||||
server,
|
||||
admission,
|
||||
importContract.name,
|
||||
context.mcpReq.signal,
|
||||
async () => {
|
||||
const path = input.path;
|
||||
const signal = context.mcpReq.signal;
|
||||
const loaded = await readImmutableEvidenceBundle(
|
||||
path,
|
||||
signal,
|
||||
resources,
|
||||
);
|
||||
if (!loaded.ok)
|
||||
return server.delivery.toCallToolResult(loaded, importContract);
|
||||
const retainedUnknownRevisions = new Set(
|
||||
bundleForSerialization(session).unknowns.map((unknown) =>
|
||||
unknownRevisionKey(unknown),
|
||||
),
|
||||
);
|
||||
if (signal.aborted)
|
||||
return server.delivery.toCallToolResult(
|
||||
err(new AnalysisCancelledError("import_evidence_bundle")),
|
||||
importContract,
|
||||
);
|
||||
const imported = session.importEvidenceBundle(loaded.value);
|
||||
return imported.ok
|
||||
? server.delivery.toCallToolResult(
|
||||
ok({
|
||||
imported: imported.value,
|
||||
unknowns_added: loaded.value.unknowns.filter(
|
||||
(unknown) =>
|
||||
!retainedUnknownRevisions.has(
|
||||
unknownRevisionKey(unknown),
|
||||
),
|
||||
).length,
|
||||
total: bundleForSerialization(session).records.length,
|
||||
}),
|
||||
importContract,
|
||||
)
|
||||
: server.delivery.toCallToolResult(imported, importContract);
|
||||
},
|
||||
),
|
||||
async (input, context) => {
|
||||
const path = input.path;
|
||||
const signal = context.mcpReq.signal;
|
||||
const loaded = await readImmutableEvidenceBundle(path, signal, resources);
|
||||
if (!loaded.ok)
|
||||
return server.delivery.toCallToolResult(loaded, importContract);
|
||||
const retainedUnknownRevisions = new Set(
|
||||
bundleForSerialization(session).unknowns.map((unknown) =>
|
||||
unknownRevisionKey(unknown),
|
||||
),
|
||||
);
|
||||
if (signal.aborted)
|
||||
return server.delivery.toCallToolResult(
|
||||
err(new AnalysisCancelledError("import_evidence_bundle")),
|
||||
importContract,
|
||||
);
|
||||
const imported = session.importEvidenceBundle(loaded.value);
|
||||
return imported.ok
|
||||
? server.delivery.toCallToolResult(
|
||||
ok({
|
||||
imported: imported.value,
|
||||
unknowns_added: loaded.value.unknowns.filter(
|
||||
(unknown) =>
|
||||
!retainedUnknownRevisions.has(unknownRevisionKey(unknown)),
|
||||
).length,
|
||||
total: bundleForSerialization(session).records.length,
|
||||
}),
|
||||
importContract,
|
||||
)
|
||||
: server.delivery.toCallToolResult(imported, importContract);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -3,37 +3,6 @@ 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,9 +7,6 @@ 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),
|
||||
);
|
||||
@@ -44,91 +41,6 @@ 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,7 +21,6 @@ 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";
|
||||
@@ -445,73 +444,6 @@ 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);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { dirname, join, sep } from "node:path";
|
||||
import { join, sep } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
@@ -138,36 +138,6 @@ it("keeps lint errors failing and visible alongside the retained warnings", asyn
|
||||
);
|
||||
});
|
||||
|
||||
it("excludes translation staging while retaining authored website errors", async () => {
|
||||
const root = await fixture();
|
||||
for (const name of [".gitignore", ".oxlintrc.json"])
|
||||
await writeFile(join(root, name), await readFile(join(repository, name)));
|
||||
const authored = "website/public/assets/authored.js";
|
||||
const staged =
|
||||
"website/.i18n-regression/site/examples/notes-electron/main.js";
|
||||
for (const name of [authored, staged]) {
|
||||
const path = join(root, name);
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
await writeFile(
|
||||
path,
|
||||
'const source = require("node:fs");\nconsole.log(source);\n',
|
||||
);
|
||||
}
|
||||
|
||||
const result = invoke(root, "lint");
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stdout).toContain("1 errors, 0 warnings");
|
||||
expect(result.stderr).toContain(authored);
|
||||
expect(await lintDiagnostics(root)).toEqual([
|
||||
expect.objectContaining({
|
||||
severity: "error",
|
||||
code: "typescript(no-var-requires)",
|
||||
filename: authored,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps malformed source failing with its parser diagnostic", async () => {
|
||||
const root = await fixture();
|
||||
await writeFile(join(root, "src/malformed.js"), "const value = ;\n");
|
||||
|
||||
@@ -1,155 +0,0 @@
|
||||
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();
|
||||
});
|
||||
@@ -3,12 +3,10 @@ import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { writeOrderedZip } from "../../../fixtures/artifactEntryOrder.js";
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
|
||||
import { artifactExtractionExecutionSchema } from "../../../../src/contracts/artifactToolContracts.js";
|
||||
import { artifactExtractionResultSchema } from "../../../../src/domain/artifactGraph.js";
|
||||
import type { BinaryTarget } from "../../../../src/domain/binaryTargetTypes.js";
|
||||
|
||||
describe("artifact extraction format support", () => {
|
||||
@@ -44,33 +42,6 @@ describe("artifact extraction format support", () => {
|
||||
});
|
||||
await expect(access(output)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it.each(["zip", "hap", "hsp", "app-pack"] as const)(
|
||||
"extracts the ZIP-backed %s package family that inventory already supports",
|
||||
async (format) => {
|
||||
const root = await createTestTempDirectory("rea-extract-zip-family-");
|
||||
const archive = join(
|
||||
root,
|
||||
`Payload.${format === "app-pack" ? "app" : format}`,
|
||||
);
|
||||
await writeOrderedZip(archive, ["payload.txt"]);
|
||||
const result = await new ArtifactProvider(process.env)
|
||||
.createClient(archiveTarget(archive, format))
|
||||
.execute(
|
||||
"extract_artifact",
|
||||
artifactExtractionExecutionSchema.parse({
|
||||
output_root: join(root, "output"),
|
||||
}),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
const extracted = artifactExtractionResultSchema.parse(
|
||||
result.value.result,
|
||||
);
|
||||
expect(
|
||||
extracted.artifacts.map(({ relative_path }) => relative_path),
|
||||
).toEqual(["payload.txt"]);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
const archiveTarget = (
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { appendFile, copyFile, mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
HOPPER_PUBLISHER,
|
||||
macHopperInstallDisclosure,
|
||||
systemMacHopperInstallHost,
|
||||
} from "../../../src/application/MacHopper.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const run = promisify(execFile);
|
||||
const itDarwin = it.skipIf(process.platform !== "darwin");
|
||||
const executableSegments = ["Contents", "MacOS", "hopper"];
|
||||
|
||||
const infoPlist = (identifier: string): string =>
|
||||
`<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>${identifier}</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>hopper</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
</dict>
|
||||
</plist>
|
||||
`;
|
||||
|
||||
/** Build a minimal `.app` whose launcher is a real signed Mach-O copy. */
|
||||
const buildBundle = async (
|
||||
root: string,
|
||||
identifier: string,
|
||||
options: { readonly sign?: boolean } = {},
|
||||
): Promise<string> => {
|
||||
const app = join(root, "Hopper Disassembler.app");
|
||||
const executable = join(app, ...executableSegments);
|
||||
await mkdir(join(app, "Contents", "MacOS"), { recursive: true });
|
||||
await copyFile("/usr/bin/true", executable);
|
||||
await writeFile(join(app, "Contents", "Info.plist"), infoPlist(identifier));
|
||||
if (options.sign !== false)
|
||||
await run("/usr/bin/codesign", [
|
||||
"--sign",
|
||||
"-",
|
||||
"--force",
|
||||
"--deep",
|
||||
"--identifier",
|
||||
identifier,
|
||||
app,
|
||||
]);
|
||||
return app;
|
||||
};
|
||||
|
||||
const host = () =>
|
||||
systemMacHopperInstallHost("/home/rea-test", { ...process.env });
|
||||
|
||||
describe("macOS Hopper publisher verification", () => {
|
||||
itDarwin(
|
||||
"rejects an ad-hoc signed bundle carrying the pinned bundle identifier",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-hopper-publisher-");
|
||||
const app = await buildBundle(root, HOPPER_PUBLISHER.bundleIdentifier);
|
||||
// The pre-pinned checks accept this bundle: `codesign --verify` succeeds
|
||||
// for ad-hoc signatures and the identifier clause alone also matches.
|
||||
await run("/usr/bin/codesign", ["--verify", "--deep", "--strict", app]);
|
||||
await expect(host().validBundle(app)).resolves.toBe(
|
||||
"unverified_publisher",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
itDarwin("rejects an unsigned bundle before any copy", async () => {
|
||||
const root = await createTestTempDirectory("rea-hopper-unsigned-");
|
||||
const app = await buildBundle(root, HOPPER_PUBLISHER.bundleIdentifier, {
|
||||
sign: false,
|
||||
});
|
||||
await expect(host().validBundle(app)).resolves.toBe("invalid_signature");
|
||||
});
|
||||
|
||||
itDarwin("rejects a bundle modified after it was signed", async () => {
|
||||
const root = await createTestTempDirectory("rea-hopper-tampered-");
|
||||
const app = await buildBundle(root, HOPPER_PUBLISHER.bundleIdentifier);
|
||||
await appendFile(join(app, ...executableSegments), "appended\n");
|
||||
await expect(host().validBundle(app)).resolves.toBe("invalid_signature");
|
||||
});
|
||||
|
||||
it("discloses the exact code requirement the installer enforces", () => {
|
||||
expect(macHopperInstallDisclosure.commands).toContain(
|
||||
`codesign --verify --strict '-R= identifier "${HOPPER_PUBLISHER.bundleIdentifier}" and anchor apple generic and certificate leaf[subject.OU] = "${HOPPER_PUBLISHER.teamIdentifier}"' <mounted-hopper.app>`,
|
||||
);
|
||||
});
|
||||
|
||||
// Opt-in positive control: point this at a mounted official Hopper bundle,
|
||||
// for example `hdiutil attach -readonly -nobrowse Hopper-6.6.0-demo.dmg`.
|
||||
// It proves the pinned requirement is satisfiable by the real publisher, so
|
||||
// a quoting or argument mistake cannot hide behind the rejection arms.
|
||||
const realApp = process.env.REA_HOPPER_MACOS_APP;
|
||||
it.skipIf(realApp === undefined)(
|
||||
"accepts the officially signed Hopper application",
|
||||
async () => {
|
||||
await expect(host().validBundle(realApp ?? "")).resolves.toBe("verified");
|
||||
},
|
||||
);
|
||||
});
|
||||
-36
@@ -4,7 +4,6 @@
|
||||
#include <winioctl.h>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cwchar>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
@@ -34,41 +33,6 @@ 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