Compare commits

..
Author SHA1 Message Date
N0zoM1z0 34661d816c fix(hopper): distinguish runtime processes from argument text
Parse procfs argument boundaries rather than searching rendered ps command text. Keep executable identity checks and deferred permission failures, eliminate the extra ps process, and put shared process observations in the serial process-boundary lane.
2026-10-13 06:52:50 +00:00
Rudy Mizrahi Celekli e74e4e951b fix(screenshot): reject invalid PNG header dimensions (#2472) 2026-10-13 15:50:44 +09:00
chAngEandchAngE 68ecf3df8c fix(browser): exclude sensitive binary lengths from historical captures (#2477)
Co-authored-by: chAngE <172472630+chAng-L19@users.noreply.github.com>
2026-10-13 14:49:47 +08:00
Stefano RizzelloandClaude Opus 5 ab62ee9dcf fix(windows): preserve caller affinity only within one processor group (#2202)
* fix(windows): preserve caller affinity only within one processor group

`spawnProcess` read the caller's affinity mask and applied it to the
suspended child unconditionally. A mask names processors relative to one
processor group, and Windows assigns each new process to a group of its
own choosing, so on hosts with more than 64 logical processors the child
is often placed in another group. `SetProcessAffinityMask` then rejects
the mask with ERROR_INVALID_PARAMETER (87) and the spawn fails, making
every owned provider process start intermittently on such hosts.

Affinity is a nicety, not an authority or isolation control, so it is now
applied only when the caller and the suspended child both occupy the same
single processor group. A child placed in another group keeps that group's
default affinity and the spawn proceeds. Job Object membership,
kill-on-owner-close policy, owner normalization and priority preservation
are unchanged, and the mask failure remains fatal within a shared group,
where it is not expected.

Single-group hosts, including every host with 64 or fewer logical
processors, are unaffected: `GetProcessGroupAffinity` reports one group
for both processes and the same mask is applied as before.

The optional process-boundary fixture gains an `affinity` observation,
and the native verification lane asserts that an owned spawn succeeds and
that the child's mask matches the caller's whenever both share a single
group.

Fixes #2181

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(windows): refuse to widen a pinned caller's affinity across groups

Addresses review feedback on the first commit.

An unconstrained caller loses nothing when Windows places an owned child
in another processor group, so that spawn proceeds with the group's
default. A caller deliberately pinned to fewer processors than its group
holds is a different case: silently accepting the default would hand the
provider tree the whole group, which `docs/installation.md` tells
operators to rely on affinity to prevent. Such a spawn now fails naming
the constraint instead. `GetProcessAffinityMask` already reports the
group's active set, which distinguishes the two without another query.

Selecting the caller's group at creation through
PROC_THREAD_ATTRIBUTE_GROUP_AFFINITY was tried first and rejected:
`CreateProcessW` fails with ERROR_INVALID_PARAMETER on a host with a
single processor group, both alongside PROC_THREAD_ATTRIBUTE_JOB_LIST and
on its own, so it cannot carry the ordinary path.

The boundary fixture's affinity observation now reports a process id's
own mask rather than its own, because a separate probe process is
assigned its own group and cannot stand in for the process that spawns
the child. Masks and the group's active set cross as fixed-width
hexadecimal strings: a mask can set bits above the safe-integer range,
where `JSON.parse` would round two different masks to one value.

The verification lane asserts the mask is inherited exactly when caller
and child share a group, and otherwise that the caller was unconstrained.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(windows): record what owned-process affinity does not preserve

A mask covering its group's whole active set does not distinguish a
caller the system placed in that group from one that selected the group
deliberately, so an owned child can still be placed elsewhere with its
processor count bounded and its group placement lost. Treating that case
as constrained instead is not available: on a multi-group host an
ordinary process is assigned a group by the system and its mask is that
group's active set, so refusing it would fail every owned spawn there.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-10-13 14:49:34 +08:00
吴佳浩Albenand吴佳浩 2c6a4fac4f fix(process): accept a trace identifier the comparison result can represent (#2488)
The trace specification owns the declared identifier vocabulary and the
comparison result echoes those identifiers verbatim into raw_trace[].event_id,
matched_variant and diagnostic event_ids. The result module restated the shared
IDENTIFIER_PATTERN by hand with a 64-character cap, so a specification with a
longer identifier validated and then its own comparison result failed to parse:
compareProcessTraces threw a raw ZodError at the caller instead of returning a
comparison.

Export the identifier schema from the specification as the single owner and
reuse it in the evaluation module, removing the capped copy. IDENTIFIER_PATTERN
has no length bound and every other consumer uses it unbounded, so the
duplicate was the outlier. Removing the bound rather than adding one keeps the
advertised trace_spec input contract unchanged; identifiers of 64 characters or
fewer behave exactly as before.

Verified with 48 process tests, 24 boundary CLI/MCP trace tests, check:fast and
verify:test-discovery on macOS arm64. The regression test failed with the
ZodError before the change and passes after it.

Co-authored-by: 吴佳浩 <wujiahao@supremind.com>
2026-10-13 14:48:26 +08:00
Mykola Dementiev c6acd19b6d fix(ida): stop the private input of a universal Mach-O at the end of the selected slice (#2291)
* test(ida): expect the private input of a universal Mach-O to end at the selected slice

Cover a universal file larger than one read chunk with another slice after the selected one, for both a middle slice and the first slice.

* fix(ida): stop the private input of a universal Mach-O at the end of the selected slice

A read chunk that starts after the slice produced a negative end offset, and Buffer.subarray counts a negative bound from the end, so the head of the following slice was written to the private input and its digest.
2026-10-13 14:48:17 +08:00
AurantiumandAurantium-47 1a1b67c888 fix(javascript): preserve POSIX runtime path case on Windows (#2422)
Use POSIX path semantics for recorded POSIX roots when reconciling runtime Evidence on Windows. Preserve Windows mapping behavior and cover implicit and explicit file roots through the reconciliation service.

Assisted-by: OpenAI GPT-6 <noreply@openai.com>

Co-authored-by: Aurantium-47 <280805072+Aurantium-47@users.noreply.github.com>
2026-10-13 14:46:28 +08:00
Rohit Ghumare 12303812a8 fix(evidence): admit bundle imports across session transitions (#2303) 2026-10-13 14:45:03 +08:00
Kaoru0822andClaude Opus 5.5 f6556ad2bc fix(pcap): order evidence ties by code point instead of host locale (#2509)
The pcap summary sorted equal-count endpoints and protocol stacks with
String#localeCompare, and Flutter build inspection sorted APK ABI
directory names the same way. localeCompare follows the host's ICU
locale, so the same capture produced differently ordered Evidence on
different hosts: under da_DK "aarp" sorts after "zz", under lt_LT
"syslog" sorts before "ssdp", and every locale puts "fe80::1" before
"fe80:1::1". Use the repository's compareUnicodeCodePoints, as the
other Evidence producers already do.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:44:09 +08:00
吴佳浩Albenand吴佳浩 d73ed6fce2 fix(domain): preserve retryable capability failures through redaction (#2494)
redactExplicitFailure rebuilds each typed failure field by field so explicit
literals are removed while the projected code stays the same. The rebuild for
AnalysisCapabilityUnavailableError carried providerId, operation, reason and
userMessage but not retryable, and the constructor defaults that field to false.
Redacting a transient capability failure therefore made it permanent and changed
the remediation shown to the caller.

Pass the field through with the same conditional-spread shape used for
userMessage. The constructor recomputes retryable from cleanupIncomplete, and
cleanup is already part of the reconstructed context, so a value that was true
before redaction stays true and a false value stays absent.

Verified with 66 error projection, access-denied, redaction and capture-failure
tests, check:fast and verify:test-discovery on macOS arm64. The regression test
failed with "expected false to be true" before the change.

Co-authored-by: 吴佳浩 <wujiahao@supremind.com>
2026-10-13 14:43:10 +08:00
Vinícius Andrade 60f771a11e fix(apple): limit already-loaded reuse to rpath dependencies (#2292)
* fix(apple): limit already-loaded reuse to rpath dependencies

dyld reuses an already-loaded image by install name only for @rpath/
dependencies (Loader.cpp:802-816) and evaluates other dependency forms
against their expanded path for each loader. When multiple images in
different directories depend on @loader_path/ libraries sharing an
install name, checking loaded images before candidate expansion caused
subsequent loaders to bind to the first loaded image's copy or appear
resolved when their own copy was absent.

Limit byInstallName registration and lookup to install names that start
with @rpath/, leaving caller-relative and literal dependencies to expand
and evaluate their own candidate paths.

Signed-off-by: Vinícius DS Andrade <95101505+viniciusdsandrade@users.noreply.github.com>

* test(apple): verify loader_path dependencies across isolated directories

Assert that multiple images depending on @loader_path/ libraries with
the same install name do not reuse already-loaded images across loaders.
When the second loader's helper is absent, its candidate path is absent
and dyld reports required-load-unresolved; when both helpers exist, each
loader resolves to its own directory.

Signed-off-by: Vinícius DS Andrade <95101505+viniciusdsandrade@users.noreply.github.com>

---------

Signed-off-by: Vinícius DS Andrade <95101505+viniciusdsandrade@users.noreply.github.com>
2026-10-13 14:40:43 +08:00
The one -Niu 650237efb0 fix(setup): pin Hopper's macOS publisher identity before install (#2481)
The macOS installer accepted any bundle that passed `codesign --verify`
and whose `Info.plist` said `com.cryptic-apps.hopper-web-4`. An ad-hoc
signed bundle with that identifier satisfies both, so a substituted DMG
could be copied to ~/Applications and launched.

Verify a pinned code requirement instead, covering the sealed bundle
identifier and the signing team together, and report a distinct
`publisher_verification_failed` code so a vendor key change is not
confused with a corrupt package.
2026-10-13 14:40:04 +08:00
吴佳浩Albenand吴佳浩 7017c4d68c fix(artifacts): read every ZIP package family extraction is asked to open (#2493)
extract_artifact carried its own copy of the ZIP package format list with five
of the eight members the domain owner declares, and used it both as the guard
that refuses a format without an extraction reader and as the selector for the
reader itself. A .hap, .hsp or App Pack target was therefore refused with
"Artifact format has no extraction reader" even though the next branch builds a
ZipArtifactReader for exactly those formats, while inventory_artifact classifies
the same path through the owner and reads it.

Import isZipPackageFormat from the domain owner and delete the duplicate list
and its predicate, removing the second representation instead of reconciling it.
The reader branch now narrows to ZipPackageFormat, which is what the
ZipArtifactReader constructor already requires.

Verified with 41 boundary extraction, ZIP integrity and detection tests,
check:fast and verify:test-discovery on macOS arm64. Reverting only the source
change fails exactly the three added families and leaves the zip control green.

Co-authored-by: 吴佳浩 <wujiahao@supremind.com>
2026-10-13 14:39:29 +08:00
YsopwnableandLuis Taffelli 141d2095f5 test(hopper): repair Linux demo setup and native verification (#2638)
* fix(verification): align Linux Hopper setup lane with current contracts

* fix(verification): retain orphan checks on clean Linux runners

* fix(verification): detect Hopper through alternate launcher paths

* fix(verification): report identified Hopper leaks before proc errors

* fix(verification): distinguish Hopper string recognition from byte fidelity

* fix(verification): report full literal decoding coverage explicitly

---------

Co-authored-by: Luis Taffelli <86675342+LuisTaffelli@users.noreply.github.com>
2026-10-13 14:39:18 +08:00
Ysopwnable 18831491cf fix(ci): ignore generated website translation staging (#2511)
Ignore generator-owned website translation staging output while preserving authored lint errors and complete diagnostics.

Verified with a real checker regression, a production translation build, complete coverage, developer/CI regression checks and native lanes.

Fixes #2508
2026-10-13 14:32:22 +08:00
40 changed files with 1205 additions and 107 deletions
+2
View File
@@ -72,3 +72,5 @@ Thumbs.db
# Complete static website output, including generated language editions.
website/_site/
# Temporary translation output prepared before replacing the complete site.
website/.i18n-*/
+1 -1
View File
@@ -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 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 or secret in str(len(value)) for secret in secrets)
safe_text = None
try:
safe_text = safe_bytes.decode("utf-8", errors="strict")
+1 -1
View File
@@ -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 request whose install name matches an
loads once per process. A later @rpath 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`.
+6 -2
View File
@@ -153,8 +153,12 @@ 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 CPU affinity and priority are
preserved. Close, cancellation, timeout, startup failure, and provider failure
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
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
+16 -4
View File
@@ -69,10 +69,22 @@ 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 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.
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.
- 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
+29 -1
View File
@@ -68,6 +68,18 @@ 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;
@@ -168,11 +180,27 @@ 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);
if (affinity != 0)
USHORT callerGroup = 0, childGroup = 0;
const bool sharedGroup = singleProcessorGroup(GetCurrentProcess(), callerGroup) &&
singleProcessorGroup(result->process.get(), childGroup) &&
callerGroup == childGroup;
if (affinity != 0 && sharedGroup)
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,6 +45,20 @@ 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"
+36
View File
@@ -662,6 +662,42 @@ 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");
+23 -4
View File
@@ -2,12 +2,16 @@ import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import { installMacHopper, type MacHopperInstallHost } from "./MacHopper.js";
import {
installMacHopper,
type MacHopperBundleVerification,
type MacHopperInstallHost,
} from "./MacHopper.js";
class FakeMacHopperHost implements MacHopperInstallHost {
readonly archive = new TextEncoder().encode("hopper-dmg");
archiveOk = true;
valid = true;
verification: MacHopperBundleVerification = "verified";
existing = false;
mountSucceeds = true;
copySucceeds = true;
@@ -15,6 +19,7 @@ class FakeMacHopperHost implements MacHopperInstallHost {
badHash = false;
unmounts = 0;
cleanups = 0;
installs = 0;
opens = 0;
replaces = false;
@@ -47,7 +52,7 @@ class FakeMacHopperHost implements MacHopperInstallHost {
return Promise.resolve();
};
appBundle = () => Promise.resolve("/mounted/Hopper Disassembler.app");
validBundle = () => Promise.resolve(this.valid);
validBundle = () => Promise.resolve(this.verification);
destinationExists = () => Promise.resolve(this.existing);
installBundle = (
_source: string,
@@ -55,6 +60,7 @@ class FakeMacHopperHost implements MacHopperInstallHost {
_stage: string,
replaceExisting: boolean,
) => {
this.installs += 1;
this.replaces = replaceExisting;
return Promise.resolve(this.copySucceeds);
};
@@ -115,7 +121,7 @@ describe("macOS Hopper installation", () => {
it("cleans and detaches after bundle validation fails", async () => {
const host = new FakeMacHopperHost();
host.valid = false;
host.verification = "invalid_signature";
await expect(installMacHopper({}, host)).resolves.toEqual({
status: "failed",
reason: "bundle",
@@ -123,4 +129,17 @@ 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);
});
});
+52 -22
View File
@@ -24,7 +24,35 @@ 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/";
const BUNDLE_IDENTIFIER = "com.cryptic-apps.hopper-web-4";
/**
* 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";
/** Stable network and command effects disclosed before macOS Hopper setup. */
export const macHopperInstallDisclosure = {
@@ -32,6 +60,7 @@ 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,
@@ -52,6 +81,7 @@ export type MacHopperInstallResult =
| "integrity"
| "mount"
| "bundle"
| "publisher_verification_failed"
| "destination_exists"
| "copy"
| "launcher_missing";
@@ -69,7 +99,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<boolean>;
validBundle(appPath: string): Promise<MacHopperBundleVerification>;
destinationExists(path: string): Promise<boolean>;
installBundle(
source: string,
@@ -124,8 +154,12 @@ export const installMacHopper = async (
return { status: "failed", reason: "mount" };
mounted = true;
const source = await host.appBundle(mountPath);
if (source === undefined || !(await host.validBundle(source)))
if (source === undefined) return { status: "failed", reason: "bundle" };
const verification = await host.validBundle(source);
if (verification === "invalid_signature")
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(
@@ -222,25 +256,21 @@ export const systemMacHopperInstallHost = (
environment,
))
)
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;
}
return "invalid_signature";
if (
!(await commandSucceeds(
"codesign",
[
"--verify",
"--strict",
`-R${HOPPER_PUBLISHER_REQUIREMENT}`,
appPath,
],
environment,
))
)
return "unverified_publisher";
return "verified";
},
async destinationExists(path) {
try {
@@ -0,0 +1,23 @@
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.",
});
});
});
+10
View File
@@ -1,3 +1,5 @@
import { HOPPER_PUBLISHER } from "./MacHopper.js";
export type SetupFailureCode =
| "unsupported_host"
| "download_failed"
@@ -10,6 +12,7 @@ export type SetupFailureCode =
| "destination_exists"
| "mount_failed"
| "bundle_invalid"
| "publisher_verification_failed"
| "copy_failed"
| "skill_install_failed"
| "cleanup_failed";
@@ -39,6 +42,7 @@ export type HopperInstallFailureReason =
| "destination_exists"
| "mount"
| "bundle"
| "publisher_verification_failed"
| "copy";
/** Map provider installer failures to stable setup codes and safe recovery. */
@@ -115,6 +119,12 @@ 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,6 +17,7 @@ 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,
@@ -400,13 +401,6 @@ 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
@@ -422,7 +416,7 @@ const requireExtractableFormat = async (
!directory &&
format !== "asar" &&
!isMachOFormat(format) &&
!isZipFormat(format)
!isZipPackageFormat(format)
)
throw new AnalysisUnsupportedTargetError(
"extract_artifact",
@@ -443,7 +437,7 @@ const createReader = async (
if (await requireExtractableFormat(path, input))
return new DirectoryArtifactReader(path);
if (format === "asar") return new AsarArtifactReader(path);
if (isZipFormat(format)) return new ZipArtifactReader(path, format);
if (isZipPackageFormat(format)) return new ZipArtifactReader(path, format);
return new MachOSliceArtifactReader(path, input.environment);
};
+2 -1
View File
@@ -144,7 +144,8 @@ const projectHar = (
(literal) =>
item.includes(literal) ||
contentBase64.includes(literal) ||
sha256.includes(literal),
sha256.includes(literal) ||
String(bytes.length).includes(literal),
);
binary_fields.push(
hidden
+130
View File
@@ -597,6 +597,136 @@ 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 = {
+8 -2
View File
@@ -427,7 +427,9 @@ const resolveDependency = async (
): Promise<Edge> => {
const current = context.loaded.get(loader);
const chain = current?.chain ?? [loader];
const loaded = context.byInstallName.get(dependency.install_name);
const loaded = dependency.install_name.startsWith("@rpath/")
? context.byInstallName.get(dependency.install_name)
: undefined;
const candidates: Candidate[] = [];
if (loaded !== undefined)
candidates.push({
@@ -506,7 +508,10 @@ const traceProcess = async (
chain: [context.root],
conditional: false,
});
if (rootSlice.install_name !== null)
if (
rootSlice.install_name !== null &&
rootSlice.install_name.startsWith("@rpath/")
)
context.byInstallName.set(rootSlice.install_name, context.root);
const pending = [context.root];
while (pending.length > 0) {
@@ -537,6 +542,7 @@ 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);
+1 -1
View File
@@ -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 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 @rpath 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,6 +116,24 @@ 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",
+1
View File
@@ -154,6 +154,7 @@ export const redactExplicitFailure = (
...(error.userMessage === undefined
? {}
: { userMessage: text(error.userMessage) }),
...(error.retryable ? { retryable: true } : {}),
},
);
if (error instanceof AnalysisResourceConstraintError)
@@ -1,4 +1,4 @@
import { posix, relative, win32 } from "node:path";
import { posix, 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)
: relative(root, value);
: posix.relative(root, value);
const portableRemainder = remainder.replaceAll("\\", "/");
if (
remainder === "" ||
+21
View File
@@ -33,3 +33,24 @@ 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,
});
});
+7 -1
View File
@@ -8,10 +8,16 @@ 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 ? undefined : { width, height };
return width === 0 ||
height === 0 ||
width > 0x7fff_ffff ||
height > 0x7fff_ffff
? undefined
: { width, height };
};
@@ -1,6 +1,7 @@
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,
@@ -100,6 +101,33 @@ 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", () => {
+4 -5
View File
@@ -13,13 +13,12 @@ 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: identifierSchema,
event_id: processTraceIdentifierSchema,
location: processObservationLocationSchema,
});
@@ -32,7 +31,7 @@ const sideResultSchema = z.union([
z.strictObject({
...sideResultShape,
status: z.literal("pass"),
matched_variant: identifierSchema.nullable(),
matched_variant: processTraceIdentifierSchema.nullable(),
}),
z.strictObject({
...sideResultShape,
@@ -53,7 +52,7 @@ const diagnosticSchema = z.strictObject({
]),
side: z.enum(["left", "right"]),
message: z.string(),
event_ids: z.array(identifierSchema),
event_ids: z.array(processTraceIdentifierSchema),
locations: z.array(processObservationLocationSchema),
});
+23 -12
View File
@@ -9,7 +9,16 @@ import {
processObservationSourceSchema,
} from "./processObservation.js";
const identifierSchema = z.string().regex(IDENTIFIER_PATTERN);
/**
* 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 cardinalitySchema = z.discriminatedUnion("kind", [
z.strictObject({ kind: z.literal("required") }),
@@ -31,7 +40,7 @@ const cardinalitySchema = z.discriminatedUnion("kind", [
]);
const eventDeclarationSchema = z.strictObject({
id: identifierSchema,
id: processTraceIdentifierSchema,
source: processObservationSourceSchema,
exact: jsonValueSchema,
ignore_fields: z
@@ -56,29 +65,31 @@ const partialOrderLanguageSchema = z.strictObject({
happens_before: z
.array(
z.strictObject({
before: identifierSchema,
after: identifierSchema,
before: processTraceIdentifierSchema,
after: processTraceIdentifierSchema,
}),
)
.default([]),
not_before: z
.array(
z.strictObject({
event: identifierSchema,
anchor: identifierSchema,
event: processTraceIdentifierSchema,
anchor: processTraceIdentifierSchema,
}),
)
.default([]),
unordered_groups: z
.array(z.strictObject({ events: z.array(identifierSchema).min(2) }))
.array(
z.strictObject({ events: z.array(processTraceIdentifierSchema).min(2) }),
)
.default([]),
prefix: z.array(identifierSchema).default([]),
suffix: z.array(identifierSchema).default([]),
prefix: z.array(processTraceIdentifierSchema).default([]),
suffix: z.array(processTraceIdentifierSchema).default([]),
});
const finiteTraceTokenSchema = z.union([
identifierSchema,
z.strictObject({ unordered: z.array(identifierSchema).min(2) }),
processTraceIdentifierSchema,
z.strictObject({ unordered: z.array(processTraceIdentifierSchema).min(2) }),
]);
const finiteTraceLanguageSchema = z.strictObject({
@@ -86,7 +97,7 @@ const finiteTraceLanguageSchema = z.strictObject({
variants: z
.array(
z.strictObject({
id: identifierSchema,
id: processTraceIdentifierSchema,
trace: z.array(finiteTraceTokenSchema),
}),
)
+3 -2
View File
@@ -23,6 +23,7 @@ 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 {
@@ -759,7 +760,7 @@ export class FlutterBuildProvider {
toolchain_capped: value.libflutter.toolchainCapped,
},
}))
.sort((left, right) => left.abi.localeCompare(right.abi));
.sort((left, right) => compareUnicodeCodePoints(left.abi, right.abi));
const flutterDetected = abis.some((entry) => entry.libapp.present);
const partial =
abis.some(
@@ -871,7 +872,7 @@ export class FlutterBuildProvider {
(left, right) =>
(preference.indexOf(left.abi) + 1 || preference.length + 1) -
(preference.indexOf(right.abi) + 1 || preference.length + 1) ||
left.abi.localeCompare(right.abi),
compareUnicodeCodePoints(left.abi, right.abi),
)[0]!
: candidates.find((candidate) => candidate.abi === abi);
if (selected === undefined)
+4 -2
View File
@@ -85,8 +85,10 @@ export class IdaWorkspace {
slice === undefined
? position + bytes.length
: Math.min(position + bytes.length, slice.offset + slice.size);
const admitted = bytes.subarray(start - position, end - position);
if (admitted.length > 0) {
// 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);
inputHash.update(admitted);
await input.write(admitted);
}
+92 -1
View File
@@ -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 } from "../domain/binaryTarget.fixture.js";
import { fat, thinMach } from "../domain/binaryTarget.fixture.js";
import {
createIdaTarget,
RecordingIdaMcp,
@@ -35,6 +35,45 @@ 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",
@@ -78,6 +117,58 @@ 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);
+31
View File
@@ -35,6 +35,37 @@ 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 = {
+18
View File
@@ -83,6 +83,24 @@ 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(
+3 -2
View File
@@ -4,6 +4,7 @@ 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. */
@@ -284,7 +285,7 @@ export const parseTsharkJsonOutput = async (
signal?.throwIfAborted();
return {
endpoints: [...endpoints]
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
.sort((a, b) => b[1] - a[1] || compareUnicodeCodePoints(a[0], b[0]))
.map(([address, packet_count]) => ({
address,
port: null,
@@ -300,7 +301,7 @@ export const parseTsharkJsonOutput = async (
tlsSniValues: [...sni],
tlsSniCount: sni.size,
protocolDistribution: [...protocols]
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
.sort((a, b) => b[1] - a[1] || compareUnicodeCodePoints(a[0], b[0]))
.map(([protocol, packet_count]) => ({ protocol, packet_count })),
protocolCount: protocols.size,
httpRequestUris: [...uris],
+47 -31
View File
@@ -12,6 +12,8 @@ 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;
@@ -92,40 +94,54 @@ const registerImportEvidenceTool = ({
resources,
importContract,
}: EvidenceToolRegistration): void => {
const admission = withAdmittedAnalysis({ kind: "session", session });
server.registerTool(
importContract.name,
toolRegistrationOptions(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);
},
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);
},
),
);
};
@@ -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);
@@ -1,6 +1,6 @@
import { spawnSync } from "node:child_process";
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
import { join, sep } from "node:path";
import { dirname, join, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { expect, it } from "vitest";
import { z } from "zod";
@@ -138,6 +138,36 @@ 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");
@@ -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();
});
@@ -3,10 +3,12 @@ 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", () => {
@@ -42,6 +44,33 @@ 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 = (
@@ -0,0 +1,108 @@
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
View File
@@ -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]);