Merge origin/main into feat/artifact-integrity-policy

Keep both new MCP extraction tests, use main's relocated Apple domain
imports, and regenerate the catalog metadata.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kaoru0822
2026-10-07 13:41:30 +00:00
co-authored by Claude Opus 5.5
228 changed files with 7188 additions and 1390 deletions
+42 -15
View File
@@ -32,7 +32,8 @@ export class JadxMcpTransport implements Transport {
readonly runId = randomUUID();
#spawned: SpawnedOwnedProviderProcess | undefined;
#supervisor: ProviderProcessSupervisor | undefined;
#buffer = Buffer.alloc(0);
#frameBuffer = Buffer.alloc(0);
#frameLength = 0;
#bytes = 0;
#started = false;
#closed = false;
@@ -61,12 +62,16 @@ export class JadxMcpTransport implements Transport {
stdin: "pipe",
});
this.#spawned = spawned;
this.#supervisor = new ProviderProcessSupervisor({
...spawned,
ownsProcessLifetime: true,
cleanup:
spawned.cleanup ?? (() => cleanupOwnedProcessGroup(spawned.ownership)),
});
this.#supervisor = new ProviderProcessSupervisor(
{
...spawned,
ownsProcessLifetime: true,
cleanup:
spawned.cleanup ??
(() => cleanupOwnedProcessGroup(spawned.ownership)),
},
{ captureStdout: false },
);
if (
spawned.process.stdin === undefined ||
spawned.process.stdin === null ||
@@ -117,6 +122,8 @@ export class JadxMcpTransport implements Transport {
async #stop(): Promise<void> {
this.#closed = true;
this.#frameBuffer = Buffer.alloc(0);
this.#frameLength = 0;
// A cancellation may race acquisition. Join it before inspecting ownership.
await this.#starting?.catch(() => undefined);
const process = this.#spawned?.process;
@@ -161,22 +168,42 @@ export class JadxMcpTransport implements Transport {
);
return;
}
this.#buffer = Buffer.concat([this.#buffer, bytes]);
try {
let newline: number;
while ((newline = this.#buffer.indexOf(10)) !== -1) {
if (newline > MAX_FRAME_BYTES)
let offset = 0;
while (offset < bytes.length) {
const newline = bytes.indexOf(10, offset);
const end = newline === -1 ? bytes.length : newline;
const fragment = bytes.subarray(offset, end);
const frameBytes = this.#frameLength + fragment.length;
if (frameBytes > MAX_FRAME_BYTES)
throw new Error(`JADX MCP frame exceeds ${MAX_FRAME_BYTES} bytes`);
const line = this.#buffer.subarray(0, newline).toString("utf8");
this.#buffer = this.#buffer.subarray(newline + 1);
this.#appendFrame(fragment, frameBytes);
if (newline === -1) return;
const line = this.#frameBuffer
.subarray(0, this.#frameLength)
.toString("utf8");
this.#frameBuffer = Buffer.alloc(0);
this.#frameLength = 0;
this.onmessage?.(deserializeMessage(line));
offset = newline + 1;
}
if (this.#buffer.length > MAX_FRAME_BYTES)
throw new Error(`JADX MCP frame exceeds ${MAX_FRAME_BYTES} bytes`);
} catch (cause) {
this.#fail(cause instanceof Error ? cause : new Error(String(cause)));
}
};
#appendFrame(fragment: Buffer, frameBytes: number): void {
if (frameBytes > this.#frameBuffer.length) {
const capacity = Math.min(
MAX_FRAME_BYTES,
Math.max(frameBytes, this.#frameBuffer.length * 2, 1),
);
const grown = Buffer.allocUnsafe(capacity);
this.#frameBuffer.copy(grown, 0, 0, this.#frameLength);
this.#frameBuffer = grown;
}
fragment.copy(this.#frameBuffer, this.#frameLength);
this.#frameLength = frameBytes;
}
#fail(error: Error): void {
this.#failure ??= error.message;
this.onerror?.(error);
+1 -1
View File
@@ -3,7 +3,7 @@ import type { OfficialToolName } from "../contracts/officialToolContracts.js";
import type { EnhancedToolName } from "../contracts/enhancedInputs.js";
import type { NativeToolName } from "../contracts/nativeToolContracts.js";
import type { ArtifactAnalysisOperation } from "../contracts/artifactToolContracts.js";
import type { ManagedToolName } from "../contracts/managedToolContracts.js";
import type { ManagedToolName } from "../contracts/managed/managedToolContracts.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { JsonValue } from "../domain/jsonValue.js";
+186
View File
@@ -0,0 +1,186 @@
import { execFile } from "node:child_process";
import { lstat, readdir, readFile, realpath, stat } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { z } from "zod";
import { BinaryTargetError } from "../domain/configurationErrors.js";
import { isPathWithinRoot } from "../domain/localPath.js";
import { parseXmlPropertyList } from "../domain/propertyListKeys.js";
import { err, ok, type Result } from "../domain/result.js";
const execFileAsync = promisify(execFile);
/** Where one app bundle layout keeps its Info.plist and program file. */
interface BundleLayout {
readonly plist: readonly string[];
readonly programs: readonly string[];
readonly programsLabel: string;
}
const BUNDLE_LAYOUTS: readonly BundleLayout[] = [
// macOS bundles keep both under Contents.
{
plist: ["Contents", "Info.plist"],
programs: ["Contents", "MacOS"],
programsLabel: "Contents/MacOS",
},
// iOS-style bundles, as extracted from an IPA, keep both at the root.
{ plist: ["Info.plist"], programs: [], programsLabel: "the bundle root" },
];
/** A resolved bundle program file and the Info.plist that declared it. */
export interface ResolvedAppBundle {
readonly executable: string;
readonly infoPlist?: string;
}
/**
* Resolve an app bundle directory to its declared program file. macOS and
* flat iOS-style layouts are read directly. An iOS app installed on a Mac is
* a wrapper whose `Wrapper` directory holds the iOS bundle; that bundle is
* found by listing `Wrapper`, never by following the `WrappedBundle` link.
*/
export const resolveAppBundleExecutable = async (
path: string,
): Promise<Result<ResolvedAppBundle, BinaryTargetError>> => {
const layout = await presentLayout(path);
if (layout !== undefined) return resolveLayoutExecutable(path, layout);
const wrapped = await wrappedBundle(path);
if (wrapped !== undefined) {
const wrappedLayout = await presentLayout(wrapped);
if (wrappedLayout !== undefined)
return resolveLayoutExecutable(wrapped, wrappedLayout);
}
return err(
new BinaryTargetError(path, "app has no readable CFBundleExecutable", {
cause: new Error(
"No Contents/Info.plist, root Info.plist, or single Wrapper/*.app bundle was found",
),
}),
);
};
const presentLayout = async (
bundle: string,
): Promise<BundleLayout | undefined> => {
for (const layout of BUNDLE_LAYOUTS)
if (await layoutPlistPresent(join(bundle, ...layout.plist))) return layout;
return undefined;
};
/**
* Whether a layout's Info.plist exists. Readable symlinks count, as they did
* when the plist was read directly; any failure other than absence, such as
* a permission denial, is left for the caller to report.
*/
const layoutPlistPresent = async (path: string): Promise<boolean> => {
try {
return (await stat(path)).isFile();
} catch (cause: unknown) {
if (isAbsence(cause)) return false;
throw cause;
}
};
const isAbsence = (cause: unknown): boolean => {
const code: unknown =
cause instanceof Error ? Reflect.get(cause, "code") : undefined;
return code === "ENOENT" || code === "ENOTDIR";
};
/** The single real `.app` directory inside an iOS-on-Mac `Wrapper`. */
const wrappedBundle = async (bundle: string): Promise<string | undefined> => {
const wrapper = join(bundle, "Wrapper");
try {
if (!(await lstat(wrapper)).isDirectory()) return undefined;
} catch (cause: unknown) {
if (isAbsence(cause)) return undefined;
throw cause;
}
const apps = (await readdir(wrapper, { withFileTypes: true })).filter(
(entry) => entry.isDirectory() && entry.name.toLowerCase().endsWith(".app"),
);
const [app] = apps;
return apps.length === 1 && app !== undefined
? join(wrapper, app.name)
: undefined;
};
const resolveLayoutExecutable = async (
bundle: string,
layout: BundleLayout,
): Promise<Result<ResolvedAppBundle, BinaryTargetError>> => {
const plistPath = join(bundle, ...layout.plist);
let name: string;
try {
const plist = await readFile(plistPath);
name =
plist.subarray(0, 6).toString("ascii") === "bplist"
? await readBinaryPlistExecutable(plistPath)
: parseXmlPlistExecutable(plist.toString("utf8"));
} catch (cause: unknown) {
return err(
new BinaryTargetError(bundle, "app has no readable CFBundleExecutable", {
cause,
}),
);
}
if (!isSafeExecutableName(name))
return err(
new BinaryTargetError(bundle, "app has an unsafe CFBundleExecutable"),
);
const programs = join(bundle, ...layout.programs);
const executable = join(programs, name);
try {
const [canonicalPrograms, canonicalExecutable] = await Promise.all([
realpath(programs),
realpath(executable),
]);
if (!isPathWithinRoot(canonicalPrograms, canonicalExecutable))
return err(
new BinaryTargetError(
bundle,
`app program file leaves ${layout.programsLabel}`,
),
);
return ok({ executable: canonicalExecutable, infoPlist: plistPath });
} catch (cause: unknown) {
return err(
new BinaryTargetError(bundle, "app program file is missing", { cause }),
);
}
};
/** Decode the top-level executable name with an XML parser, not a pattern. */
const parseXmlPlistExecutable = (plist: string): string => {
// An unrelated `__proto__` entry must not make the bundle unreadable.
const { value } = parseXmlPropertyList(plist);
const executable = executableEntrySchema.safeParse(value);
if (!executable.success) throw new Error("CFBundleExecutable is missing");
return executable.data.CFBundleExecutable;
};
const executableEntrySchema = z.looseObject({ CFBundleExecutable: z.string() });
const readBinaryPlistExecutable = async (plistPath: string): Promise<string> =>
// `-n` strips only the newline plutil appends; it requires macOS 12+.
(
await execFileAsync("/usr/bin/plutil", [
"-extract",
"CFBundleExecutable",
"raw",
"-n",
"-o",
"-",
plistPath,
])
).stdout;
const isSafeExecutableName = (name: string): boolean =>
name.length > 0 &&
name !== "." &&
name !== ".." &&
!name.includes("\0") &&
!/[/\\]/u.test(name);
+13 -82
View File
@@ -3,22 +3,19 @@ import { createHash } from "node:crypto";
import {
access,
open,
readFile,
realpath,
stat,
type FileHandle,
} from "node:fs/promises";
import { execFile } from "node:child_process";
import { extname, isAbsolute, join, resolve } from "node:path";
import { promisify } from "node:util";
import { extname, isAbsolute, resolve } from "node:path";
import { z } from "zod";
import { isPathWithinRoot } from "../domain/localPath.js";
import { parseXmlPropertyList } from "../domain/propertyListKeys.js";
import { BinaryTargetError } from "../domain/configurationErrors.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import { err, ok, type Result } from "../domain/result.js";
import {
resolveAppBundleExecutable,
type ResolvedAppBundle,
} from "./AppBundleExecutable.js";
import {
validateDosComLength,
type ExecutableFormatHint,
@@ -35,8 +32,6 @@ import {
type ExecutableMetadata,
} from "../domain/binaryTarget.js";
const execFileAsync = promisify(execFile);
/**
* Resolve and classify a readable local target before a provider is selected.
* FAT Mach-O inputs select only a host-compatible architecture so setup remains
@@ -55,7 +50,9 @@ export const parseBinaryTarget = async (
const canonical = await realpath(candidate);
const resolved = await resolveAppBundle(canonical);
if (!resolved.ok) return err(resolved.error);
const path = resolved.value;
const { executable: path, infoPlist } = resolved.value;
const bundle =
infoPlist === undefined ? {} : { bundleInfoPlist: infoPlist };
const handle = await open(path, "r");
try {
if (!(await handle.stat()).isFile())
@@ -107,6 +104,7 @@ export const parseBinaryTarget = async (
return ok({
path,
sourcePath: process.platform === "win32" ? candidate : canonical,
...bundle,
sha256: await sha256Handle(handle),
kind: "executable",
...detected.value,
@@ -216,89 +214,22 @@ const sha256Handle = async (handle: FileHandle): Promise<string> => {
const resolveAppBundle = async (
path: string,
): Promise<Result<string, BinaryTargetError>> => {
): Promise<Result<ResolvedAppBundle, BinaryTargetError>> => {
const metadata = await stat(path);
if (!metadata.isDirectory()) return ok(path);
if (!metadata.isDirectory()) return ok({ executable: path });
if (extname(path).toLowerCase() !== ".app")
return err(
new BinaryTargetError(
path,
"this opening route requires a file or macOS app bundle",
"this opening route requires a file or app bundle",
{
constraint: "directory_requires_file",
},
),
);
const plistPath = join(path, "Contents", "Info.plist");
let name: string;
try {
const plist = await readFile(plistPath);
name =
plist.subarray(0, 6).toString("ascii") === "bplist"
? await readBinaryPlistExecutable(plistPath)
: parseXmlPlistExecutable(plist.toString("utf8"));
} catch (cause: unknown) {
return err(
new BinaryTargetError(path, "app has no readable CFBundleExecutable", {
cause,
}),
);
}
if (!isSafeExecutableName(name))
return err(
new BinaryTargetError(path, "app has an unsafe CFBundleExecutable"),
);
const programs = join(path, "Contents", "MacOS");
const executable = join(programs, name);
try {
const [canonicalPrograms, canonicalExecutable] = await Promise.all([
realpath(programs),
realpath(executable),
]);
if (!isPathWithinRoot(canonicalPrograms, canonicalExecutable))
return err(
new BinaryTargetError(path, "app program file leaves Contents/MacOS"),
);
return ok(canonicalExecutable);
} catch (cause: unknown) {
return err(
new BinaryTargetError(path, "app program file is missing", { cause }),
);
}
return resolveAppBundleExecutable(path);
};
/** Decode the top-level executable name with an XML parser, not a pattern. */
const parseXmlPlistExecutable = (plist: string): string => {
// An unrelated `__proto__` entry must not make the bundle unreadable.
const { value } = parseXmlPropertyList(plist);
const executable = executableEntrySchema.safeParse(value);
if (!executable.success) throw new Error("CFBundleExecutable is missing");
return executable.data.CFBundleExecutable;
};
const executableEntrySchema = z.looseObject({ CFBundleExecutable: z.string() });
const readBinaryPlistExecutable = async (plistPath: string): Promise<string> =>
// `-n` strips only the newline plutil appends; it requires macOS 12+.
(
await execFileAsync("/usr/bin/plutil", [
"-extract",
"CFBundleExecutable",
"raw",
"-n",
"-o",
"-",
plistPath,
])
).stdout;
const isSafeExecutableName = (name: string): boolean =>
name.length > 0 &&
name !== "." &&
name !== ".." &&
!name.includes("\0") &&
!/[/\\]/u.test(name);
const readExecutableMetadata = async (
handle: FileHandle,
hostArchitecture: NodeJS.Architecture,
+1 -1
View File
@@ -12,7 +12,7 @@ import type { ArtifactAnalysisOperation } from "../contracts/artifactToolContrac
import {
isManagedToolName,
type ManagedToolName,
} from "../contracts/managedToolContracts.js";
} from "../contracts/managed/managedToolContracts.js";
import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { type AnalysisError } from "../domain/analysisErrorBase.js";
+15
View File
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
import {
installLinuxHopper,
linuxHopperLauncherDigestSupported,
linuxHopperInstallDisclosure,
linuxPackageManagerCommands,
linuxSharedLibrariesAvailable,
@@ -93,6 +94,20 @@ describe("Linux Hopper host classification", () => {
});
describe("Linux Hopper installation", () => {
it.each([
[
"Debian and Arch",
"0294ced141cc373468ee22d8343e7dac41980cb05a937994ca81c9f09afe7ded",
],
["RPM", "1339f9e58377442b0c6fcb0dfc3cec20d593cc557408521fad9a00dbc6b8da13"],
])("accepts the pinned %s launcher build", (_, digest) => {
expect(linuxHopperLauncherDigestSupported(digest)).toBe(true);
});
it("rejects an unverified launcher build", () => {
expect(linuxHopperLauncherDigestSupported("0".repeat(64))).toBe(false);
});
it("discloses the exact download, integrity evidence, and privileged command", () => {
expect(linuxHopperInstallDisclosure("deb", false)).toEqual({
downloadUrl:
+9 -3
View File
@@ -11,8 +11,10 @@ import { execFileOutput } from "../process/ExecFileOutput.js";
const execFileAsync = promisify(execFile);
const DOWNLOAD_PREFIX = "https://www.hopperapp.com:443/downloader/public/";
const MAX_PACKAGE_BYTES = 100_000_000;
const SUPPORTED_HOPPER_SHA256 =
"0294ced141cc373468ee22d8343e7dac41980cb05a937994ca81c9f09afe7ded";
const SUPPORTED_HOPPER_SHA256 = new Set([
"0294ced141cc373468ee22d8343e7dac41980cb05a937994ca81c9f09afe7ded",
"1339f9e58377442b0c6fcb0dfc3cec20d593cc557408521fad9a00dbc6b8da13",
]);
interface LinuxHopperRelease {
readonly filename: string;
readonly file_length: string;
@@ -262,7 +264,7 @@ export const linuxHopperBinarySupported = async (
try {
const hash = createHash("sha256");
for await (const chunk of createReadStream(path)) hash.update(chunk);
return hash.digest("hex") === SUPPORTED_HOPPER_SHA256;
return linuxHopperLauncherDigestSupported(hash.digest("hex"));
} catch (cause: unknown) {
// best-effort cleanup: optional build probing; unreadable means unsupported.
void cause;
@@ -270,6 +272,10 @@ export const linuxHopperBinarySupported = async (
}
};
/** Match a launcher extracted from one of the pinned official Linux packages. */
export const linuxHopperLauncherDigestSupported = (digest: string): boolean =>
SUPPORTED_HOPPER_SHA256.has(digest);
/** Interpret ldd output conservatively so a present but broken launcher is unhealthy. */
export const linuxSharedLibrariesAvailable = (output: string): boolean =>
!/(?:=>\s+not found|error while loading shared libraries)/iu.test(output);
+1 -1
View File
@@ -3,7 +3,7 @@ import { z } from "zod";
import type { AnalysisOperationPort } from "./AnalysisProvider.js";
import type { EnhancedResult } from "./EnhancedToolTypes.js";
import type { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
import { interfaceBuilderAnalysisSchema } from "../domain/interfaceBuilderGraph.js";
import { interfaceBuilderAnalysisSchema } from "../domain/apple/interfaceBuilderGraph.js";
import {
nativeInvestigationGraphSchema,
nativeInvestigationTraceSchema,
+5
View File
@@ -52,6 +52,11 @@ export class FakeSetupHost implements SetupHost {
linuxDistribution = (): Promise<LinuxDistribution | undefined> =>
Promise.resolve(this.distribution);
hopperPath = (): Promise<string | undefined> => Promise.resolve(this.hopper);
initialSetupState = async (scope?: DoctorScope) => ({
...(this.hopper === undefined ? {} : { hopperPath: this.hopper }),
providerEnvironment: await this.providerEnvironment(),
doctor: await this.doctor(scope),
});
providerEnvironment = (): Promise<SetupProviderEnvironment> =>
Promise.resolve({
...(this.hopper === undefined
@@ -0,0 +1,51 @@
import { expect, it } from "vitest";
import { runSetup } from "./Setup.js";
import { FakeSetupHost, options } from "./Setup.fixture.js";
it("uses the shared initial host snapshot for setup planning", async () => {
const host = new FakeSetupHost();
host.hopperPath = () => {
throw new Error("setup snapshot should provide the Hopper path");
};
host.providerEnvironment = () => {
throw new Error("setup snapshot should provide provider settings");
};
host.initialSetupState = async (scope) => ({
hopperPath: "/snapshot/Hopper",
providerEnvironment: { HOPPER_LAUNCHER_PATH: "/snapshot/Hopper" },
doctor: await host.doctor(scope),
});
host.clients = [{ name: "codex", configPath: "/codex.json" }];
const result = await runSetup(
{ ...options(false), dryRun: true, clientIds: ["codex"] },
host,
);
expect(result.status).toBe("planned");
expect(result.plannedActions.map(({ id }) => id)).toContain(
"configure_client:codex",
);
expect(host.doctorCalls).toBe(1);
});
it("refreshes doctor after approved setup changes", async () => {
const host = new FakeSetupHost();
host.doctorHealthy = false;
host.skill = "unchanged";
host.clients = [{ name: "codex", configPath: "/codex.json" }];
const configureClient = host.configureClient;
host.configureClient = (client, providerEnvironment, command) => {
host.doctorHealthy = true;
return configureClient(client, providerEnvironment, command);
};
const result = await runSetup(
{ ...options(true), clientIds: ["codex"], installSkill: false },
host,
);
expect(result.doctor.healthy).toBe(true);
expect(host.doctorCalls).toBe(2);
});
+12 -2
View File
@@ -42,8 +42,15 @@ export const runSetup = async (
);
const unsupported = await hostRemediation(host, false);
if (unsupported !== undefined) return fail(unsupported);
let hopperPath = await host.hopperPath();
let providerEnvironment = await initialProviderEnvironment(host, hopperPath);
const initialState = await host.initialSetupState?.(options.readinessScope);
let hopperPath =
initialState === undefined
? await host.hopperPath()
: initialState.hopperPath;
let providerEnvironment =
initialState === undefined
? await initialProviderEnvironment(host, hopperPath)
: initialState.providerEnvironment;
const discovery = await discoverSetupState({
host,
providerEnvironment,
@@ -51,6 +58,9 @@ export const runSetup = async (
proposeHopper:
options.proposeHopper ?? (confirm !== undefined && !options.structured),
doctorScope: options.readinessScope,
...(initialState === undefined
? {}
: { initialDoctor: initialState.doctor }),
});
clientStates = discovery.clientStates;
const clientSelectionAllowed =
+25 -1
View File
@@ -22,7 +22,12 @@ import {
} from "./SetupClientConfiguration.js";
import { setupInstallFailure } from "./SetupInstallFailure.js";
import { providerRegistrationEnvironment } from "./SetupRegistrationEnvironment.js";
import type { SetupHost, SetupProviderEnvironment } from "./SetupTypes.js";
import type {
SetupHost,
SetupInitialState,
SetupProviderEnvironment,
} from "./SetupTypes.js";
import type { DoctorScope } from "./Doctor.js";
/** Resolve the executable and arguments used in a managed MCP registration. */
export const setupRegistrationCommand = (
@@ -91,6 +96,25 @@ export const systemSetupHost = (
macosVersion: () => doctorHost.macosVersion(),
linuxDistribution: readLinuxDistribution,
hopperPath: async () => (await runDoctor(undefined, doctorHost)).hopperPath,
initialSetupState: async (
scope?: DoctorScope,
): Promise<SetupInitialState> => {
const diagnosis = await runDoctor(undefined, doctorHost, scope);
return {
...(diagnosis.hopperPath === undefined
? {}
: { hopperPath: diagnosis.hopperPath }),
providerEnvironment: {
...providerRegistrationEnvironment(
diagnosis.providerInspections ?? [],
),
...(diagnosis.hopperPath === undefined
? {}
: { HOPPER_LAUNCHER_PATH: diagnosis.hopperPath }),
},
doctor: diagnosis,
};
},
providerEnvironment: async () => {
const diagnosis = await runDoctor(undefined, doctorHost);
return {
+4 -1
View File
@@ -16,6 +16,7 @@ import type {
} from "./SetupTypes.js";
import type { SetupClient } from "./SupportedClients.js";
import type { DoctorScope } from "./Doctor.js";
import type { DoctorReport } from "./Doctor.js";
/** Read-only setup facts shared by client selection and preflight. */
export interface SetupDiscovery {
@@ -36,8 +37,10 @@ export const discoverSetupState = async (input: {
readonly forceHopperInstall: boolean;
readonly proposeHopper: boolean;
readonly doctorScope: DoctorScope | undefined;
readonly initialDoctor?: DoctorReport;
}): Promise<SetupDiscovery> => {
const initialDoctor = await input.host.doctor(input.doctorScope);
const initialDoctor =
input.initialDoctor ?? (await input.host.doctor(input.doctorScope));
const linuxHopperRepairNeeded = initialDoctor.checks.some(
({ name, ok, detail }) =>
!ok &&
+8
View File
@@ -9,6 +9,13 @@ import type {
/** Exact non-secret provider variables propagated into managed registrations. */
export type SetupProviderEnvironment = Readonly<Record<string, string>>;
/** Read-only host facts shared by the initial setup plan. */
export interface SetupInitialState {
readonly hopperPath?: string;
readonly providerEnvironment: SetupProviderEnvironment;
readonly doctor: DoctorReport;
}
/** Result of one backup/write/readback transaction. */
export type ClientConfigurationResult =
| {
@@ -38,6 +45,7 @@ export interface SetupHost {
macosVersion(): Promise<string | undefined>;
linuxDistribution(): Promise<LinuxDistribution | undefined>;
hopperPath(): Promise<string | undefined>;
initialSetupState?(scope?: DoctorScope): Promise<SetupInitialState>;
installHopper(replaceExisting: boolean): Promise<SetupHopperInstallResult>;
providerEnvironment?(): Promise<SetupProviderEnvironment>;
detectedClients(): Promise<readonly SetupClient[]>;
@@ -1,16 +1,16 @@
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { Evidence } from "../domain/evidence.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { Evidence } from "../../domain/evidence.js";
import {
appleApplicationProjectionInputSchema,
projectAppleApplication,
} from "../domain/appleApplication.js";
import type { Result } from "../domain/result.js";
import { APPLE_APPLICATION_PROVIDER } from "./InvestigationProviders.js";
import { projectInventoryEvidence } from "./InventoryProjectionEvidence.js";
} from "../../domain/apple/appleApplication.js";
import type { Result } from "../../domain/result.js";
import { APPLE_APPLICATION_PROVIDER } from "../InvestigationProviders.js";
import { projectInventoryEvidence } from "../InventoryProjectionEvidence.js";
const OPERATION = "project_apple_application_graph" as const;
/** Project authenticated IPA inventory Evidence into Apple application evidence. */
/** Project authenticated IPA or macOS app inventory Evidence into Apple application evidence. */
export const projectAppleApplicationEvidence = (
rawInput: unknown,
): Result<Evidence, AnalysisError> => {
@@ -21,7 +21,7 @@ export const projectAppleApplicationEvidence = (
operation: OPERATION,
predicateType: "rea.apple-application-graph",
provider: APPLE_APPLICATION_PROVIDER,
subjectFormat: () => "ipa",
subjectFormat: (first) => first.subject?.format ?? "unknown",
protocolError: "Apple application projection produced an invalid result",
});
};
@@ -132,7 +132,7 @@ export const bindExecutionTarget = (
if (
result.value.subject !== null &&
result.value.subject.sha256 !== target.sha256 &&
!isArtifactInventorySubject(operation, result.value.subject, target)
!isArtifactBundleSubject(operation, result.value.subject, target)
)
return err(
new ProviderAdapterError(
@@ -143,10 +143,12 @@ export const bindExecutionTarget = (
return ok({ ...result.value, subject: result.value.subject ?? subject });
};
const isArtifactInventorySubject = (
const isArtifactBundleSubject = (
operation: AnalysisOperation,
subject: EvidenceSubjectTarget,
target: BinaryTarget,
): boolean =>
(operation === "inventory_artifact" || operation === "inspect_artifact") &&
(operation === "inventory_artifact" ||
operation === "inspect_artifact" ||
operation === "extract_artifact") &&
subject.path === (target.sourcePath ?? target.path);
@@ -12,7 +12,7 @@ import {
import type { JavaScriptApplicationGraph } from "../../domain/javascript/javascriptApplicationGraph.js";
import type { JavaScriptSemanticGraph } from "../../domain/javascript/javascriptSemanticGraph.js";
import { javascriptRuntimeReconciliationResultSchema } from "../../domain/javascript/javascriptRuntimeReconciliationSchemas.js";
import { managedApplicationGraphResultSchema } from "../../domain/managedApplicationGraph.js";
import { managedApplicationGraphResultSchema } from "../../domain/managed/managedApplicationGraph.js";
/** Supported immutable source for an application-level graph workflow. */
export interface ApplicationGraphEvidenceSource {
@@ -268,11 +268,12 @@ const addSourceMapEdge = (
context: JavaScriptArtifactGraphContext,
input: FindingInput<StaticSourceMap>,
): void => {
const resolvedPath = resolveArtifactPath(
input.value.declared_url,
input.file.path,
context.filesByPath,
);
const resolvedPath = resolveArtifactPathByContext({
declaredPath: input.value.declared_url,
sourcePath: input.file.path,
context: "url-reference",
files: context.filesByPath,
}).resolved_path;
const resolvedFile =
resolvedPath === null ? undefined : context.filesByPath.get(resolvedPath);
const resolvedNode =
@@ -341,17 +342,26 @@ const resolveReference = (
? null
: { path: `${sourcePath}#module:${specifier}`, file, node: module };
}
const path = resolveArtifactPath(
specifier,
sourcePath,
context.filesByPath,
reference.kind === "require"
? "require"
: reference.kind === "static-import" ||
reference.kind === "dynamic-import"
? "import"
: undefined,
);
// Worker scripts are URLs relative to the script, not module specifiers.
const path =
reference.kind === "worker" || reference.kind === "service-worker"
? resolveArtifactPathByContext({
declaredPath: specifier,
sourcePath,
context: "url-reference",
files: context.filesByPath,
}).resolved_path
: resolveArtifactPath(
specifier,
sourcePath,
context.filesByPath,
reference.kind === "require"
? "require"
: reference.kind === "static-import" ||
reference.kind === "dynamic-import"
? "import"
: undefined,
);
if (path === null) return null;
const file = context.filesByPath.get(path);
const node = context.fileNodes.get(path);
@@ -562,6 +562,61 @@ describe("contextual JavaScript module identity", () => {
});
});
describe("url-reference JavaScript artifact path resolution", () => {
it("resolves sibling paths and rejects external URL forms", () => {
const files = fileMap([
file("dist/app.js", "root"),
file("dist/app.js.map", "root"),
file("dist/worker.js", "root"),
]);
expect(
resolve({
declaredPath: "app.js.map",
sourcePath: "dist/app.js",
context: "url-reference",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "dist/app.js.map",
});
expect(
resolve({
declaredPath: "app.js.map?v=1#section",
sourcePath: "dist/app.js",
context: "url-reference",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "dist/app.js.map",
});
expect(
resolve({
declaredPath: "//cdn.example.com/app.js.map",
sourcePath: "dist/app.js",
context: "url-reference",
files,
}),
).toMatchObject({
resolution_status: "external",
resolved_path: null,
});
expect(
resolve({
declaredPath: "https://cdn.example.com/app.js.map",
sourcePath: "dist/app.js",
context: "url-reference",
files,
}),
).toMatchObject({
resolution_status: "external",
resolved_path: null,
});
});
});
const resolve = (input: ResolveArtifactPathInput) =>
resolveArtifactPathByContext(input);
@@ -13,7 +13,8 @@ type ArtifactPathResolutionContext =
| "package-entrypoint"
| "filesystem-expression"
| "module-specifier"
| "html-reference";
| "html-reference"
| "url-reference";
type UnresolvedArtifactPathStatus =
| "not-found"
@@ -127,6 +128,7 @@ const contextualCandidate = (
const { context } = input;
const declared =
context === "html-reference" ||
context === "url-reference" ||
(context === "module-specifier" && input.moduleKind !== "require")
? stripQueryAndFragment(input.declaredPath)
: input.declaredPath;
@@ -140,9 +142,9 @@ const contextualCandidate = (
]);
if (!declared.startsWith(".") && !declared.startsWith("/"))
return bareModuleCandidate(input, declared);
} else if (hasScheme(declared))
} else if (looksExternal(declared))
return unresolvedOutcome(input, "external", [
"URL schemes are outside this local artifact path context.",
"URL schemes and protocol-relative URLs are outside this local artifact path context.",
]);
const relative = declared.startsWith("/") ? declared.slice(1) : declared;
return declared.startsWith("/")
@@ -3,19 +3,19 @@ import { z } from "zod";
import {
AnalysisInputError,
AnalysisProtocolError,
} from "../domain/analysisErrorCore.js";
import { type AnalysisError } from "../domain/analysisErrorBase.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
} from "../../domain/analysisErrorCore.js";
import { type AnalysisError } from "../../domain/analysisErrorBase.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import {
managedApplicationGraphResultSchema,
projectManagedApplicationGraph,
projectManagedApplicationGraphInputSchema,
type ManagedApplicationGraphResult,
type ProjectManagedApplicationGraphInput,
} from "../domain/managedApplicationGraph.js";
import { err, ok, type Result } from "../domain/result.js";
import { MANAGED_WORKFLOW_PROVIDER } from "./InvestigationProviders.js";
} from "../../domain/managed/managedApplicationGraph.js";
import { err, ok, type Result } from "../../domain/result.js";
import { MANAGED_WORKFLOW_PROVIDER } from "../InvestigationProviders.js";
const OPERATION = "project_managed_application_graph" as const;
@@ -8,22 +8,22 @@ import {
managedMemberComparisonResultSchema,
parseManagedMemberEvidence,
type CompareManagedMembersInput,
} from "../domain/managedMemberComparison.js";
} from "../../domain/managed/managedMemberComparison.js";
import {
AnalysisInputError,
AnalysisProtocolError,
} from "../domain/analysisErrorCore.js";
import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
import { type AnalysisError } from "../domain/analysisErrorBase.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { parseBinaryTarget } from "./BinaryTargetResolver.js";
import { err, ok, type Result } from "../domain/result.js";
import { inspectManagedMembersBytes } from "../dotnet/ManagedMemberInspector.js";
} from "../../domain/analysisErrorCore.js";
import { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
import { type AnalysisError } from "../../domain/analysisErrorBase.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import { parseBinaryTarget } from "../BinaryTargetResolver.js";
import { err, ok, type Result } from "../../domain/result.js";
import { inspectManagedMembersBytes } from "../../dotnet/ManagedMemberInspector.js";
import {
MANAGED_STATIC_PROVIDER,
MANAGED_WORKFLOW_PROVIDER,
} from "./InvestigationProviders.js";
} from "../InvestigationProviders.js";
/** Compare managed members from input parsed by a trusted adapter. */
export const compareManagedMembersEvidenceValidated = (
@@ -3,18 +3,18 @@ import { z } from "zod";
import {
AnalysisInputError,
AnalysisProtocolError,
} from "../domain/analysisErrorCore.js";
import { type AnalysisError } from "../domain/analysisErrorBase.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
} from "../../domain/analysisErrorCore.js";
import { type AnalysisError } from "../../domain/analysisErrorBase.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import {
managedNativeVerificationInputSchema,
verifyManagedNativeBoundaries,
type ManagedNativeVerificationInput,
type ManagedNativeVerificationResult,
} from "../domain/managedNativeVerification.js";
import { err, ok, type Result } from "../domain/result.js";
import { MANAGED_WORKFLOW_PROVIDER } from "./InvestigationProviders.js";
} from "../../domain/managed/managedNativeVerification.js";
import { err, ok, type Result } from "../../domain/result.js";
import { MANAGED_WORKFLOW_PROVIDER } from "../InvestigationProviders.js";
const OPERATION = "verify_managed_native_boundaries" as const;
@@ -2,13 +2,13 @@ import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import { MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE } from "../contracts/managedWorkflowExamples.js";
import { MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE } from "../../contracts/managed/managedWorkflowExamples.js";
import {
importManagedReconstruction,
managedReconstructionImportInputSchema,
} from "../domain/managedReconstruction.js";
import { managedMemberInspectionSchema } from "../domain/managedArtifact.js";
import { createEvidence } from "../domain/evidence.js";
} from "../../domain/managed/managedReconstruction.js";
import { managedMemberInspectionSchema } from "../../domain/managed/managedArtifact.js";
import { createEvidence } from "../../domain/evidence.js";
import { importManagedReconstructionEvidence } from "./ManagedReconstructionService.js";
const exampleInput = () =>
@@ -3,18 +3,18 @@ import { z } from "zod";
import {
AnalysisInputError,
AnalysisProtocolError,
} from "../domain/analysisErrorCore.js";
import { type AnalysisError } from "../domain/analysisErrorBase.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
} from "../../domain/analysisErrorCore.js";
import { type AnalysisError } from "../../domain/analysisErrorBase.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import {
importManagedReconstruction,
managedReconstructionImportInputSchema,
type ManagedReconstructionImportInput,
type ManagedReconstructionImportResult,
} from "../domain/managedReconstruction.js";
import { err, ok, type Result } from "../domain/result.js";
import { MANAGED_WORKFLOW_PROVIDER } from "./InvestigationProviders.js";
} from "../../domain/managed/managedReconstruction.js";
import { err, ok, type Result } from "../../domain/result.js";
import { MANAGED_WORKFLOW_PROVIDER } from "../InvestigationProviders.js";
const OPERATION = "import_managed_reconstruction" as const;
+4 -4
View File
@@ -7,12 +7,12 @@ import {
type ProviderIdentity,
type ExecutionOptions,
} from "../application/AnalysisProvider.js";
import { inspectBundleKeyedArchive } from "./KeyedArchiveReader.js";
import { inspectBundleKeyedArchive } from "./apple/KeyedArchiveReader.js";
import { basename, dirname } from "node:path";
import { inventoryArtifact } from "../application/ArtifactInventory.js";
import { extractArtifact } from "../application/ArtifactExtraction.js";
import { analyzeInterfaceBuilderBundle } from "../application/InterfaceBuilderAnalysis.js";
import { analyzeAppleAssetCatalogs } from "../application/AppleAssetCatalogAnalysis.js";
import { analyzeInterfaceBuilderBundle } from "./apple/InterfaceBuilderAnalysis.js";
import { analyzeAppleAssetCatalogs } from "./apple/AppleAssetCatalogAnalysis.js";
import {
ARTIFACT_ANALYSIS_OPERATIONS,
artifactInventoryInputSchema,
@@ -24,7 +24,7 @@ import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.
import { ArtifactOperationError } from "../domain/artifactOperationError.js";
import { type AnalysisError } from "../domain/analysisErrorBase.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { interfaceBuilderLimitsSchema } from "../domain/interfaceBuilderGraph.js";
import { interfaceBuilderLimitsSchema } from "../domain/apple/interfaceBuilderGraph.js";
import { err, ok } from "../domain/result.js";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
import {
+23 -8
View File
@@ -143,14 +143,29 @@ const asarFailure = (
path: string,
operation: string,
cause: unknown,
): ArtifactReaderFailure =>
cause instanceof ArtifactReaderFailure
? cause
: new ArtifactReaderFailure(
"format",
`Malformed or unreadable ASAR during ${operation}: ${path}`,
{ cause },
);
): ArtifactReaderFailure => {
if (cause instanceof ArtifactReaderFailure) return cause;
if (isFilesystemFailure(cause))
return new ArtifactReaderFailure(
"io",
`Could not ${operation} ASAR at ${path}: ${cause.message}`,
{ cause },
);
return new ArtifactReaderFailure(
"format",
`Malformed ASAR during ${operation}: ${path}`,
{ cause },
);
};
const isFilesystemFailure = (
cause: unknown,
): cause is NodeJS.ErrnoException & Error =>
cause instanceof Error &&
"errno" in cause &&
typeof cause.errno === "number" &&
"syscall" in cause &&
typeof cause.syscall === "string";
const isMissingFile = (cause: unknown): boolean =>
typeof cause === "object" &&
+1 -1
View File
@@ -85,7 +85,7 @@ export class DirectoryArtifactReader implements ArtifactReader {
);
const handle = await open(
entry.adapterKey,
constants.O_RDONLY | constants.O_NOFOLLOW,
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
);
try {
const observed = await handle.stat();
+32 -1
View File
@@ -23,6 +23,13 @@ const attachOutputSchema = z.object({
}),
),
});
const infoOutputSchema = z.object({
images: z.array(
z.object({
"system-entities": z.array(z.object({ "dev-entry": z.string() })),
}),
),
});
/** Narrow host seam for tested, shell-free hdiutil lifecycle operations. */
export interface NativeDmgHost {
@@ -113,7 +120,10 @@ export class NativeDmgArtifactReader implements ArtifactReader {
});
this.#provenance.push(command(["detach", device], ["mount"]));
} catch (cause: unknown) {
detachFailure ??= cause;
// Detaching a synthesized APFS container also ejects the image that
// backs it, so a later whole disk of the same image may already be
// gone. Only a device that is still attached is a cleanup failure.
if (await this.#isAttached(device)) detachFailure ??= cause;
}
}
this.#devices = [];
@@ -131,6 +141,27 @@ export class NativeDmgArtifactReader implements ArtifactReader {
);
}
/**
* Report whether hdiutil still lists a device; unknown state counts as
* attached. Like detach, this cleanup query runs after the inventory
* snapshot has captured provenance, so it is not recorded there.
*/
async #isAttached(device: string): Promise<boolean> {
try {
const info = await runChecked(this.host, ["info", "-plist"], undefined, {
timeoutMs: DETACH_TIMEOUT_MS,
});
const parsed = infoOutputSchema.parse(parse(info.stdout));
return parsed.images.some((image) =>
image["system-entities"].some(
(entity) => entity["dev-entry"] === device,
),
);
} catch {
return true;
}
}
async attach(signal?: AbortSignal): Promise<void> {
await runChecked(this.host, ["verify", this.path], signal);
this.#provenance.push(command(["verify", this.path], ["read"]));
@@ -1,14 +1,14 @@
import { createHash } from "node:crypto";
import { lstat } from "node:fs/promises";
import { DirectoryArtifactReader } from "../artifacts/DirectoryArtifactReader.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
import { ArtifactReaderFailure } from "../ArtifactReader.js";
import { analyzeInterfaceBuilderBundle } from "./InterfaceBuilderAnalysis.js";
import {
appleAssetCatalogInputSchema,
parseAppleAssetCatalogRecords,
projectAppleAssetCatalogPage,
} from "../domain/appleAssetCatalog.js";
import { execFileOutput } from "../process/ExecFileOutput.js";
} from "../../domain/apple/appleAssetCatalog.js";
import { execFileOutput } from "../../process/ExecFileOutput.js";
const ASSETUTIL = "/usr/bin/assetutil";
const MAX_CATALOG_BYTES = 64 * 1024 * 1024;
@@ -105,7 +105,7 @@ export const analyzeAppleAssetCatalogs = async (input: {
const inspectAssetCatalogEntry = async (input: {
readonly reader: DirectoryArtifactReader;
readonly entry: import("../artifacts/ArtifactReader.js").ArtifactEntry;
readonly entry: import("../ArtifactReader.js").ArtifactEntry;
readonly runAssetUtil: (
path: string,
signal?: AbortSignal,
@@ -237,7 +237,7 @@ const runAssetUtil = async (
const digestBounded = async (
reader: DirectoryArtifactReader,
entry: import("../artifacts/ArtifactReader.js").ArtifactEntry,
entry: import("../ArtifactReader.js").ArtifactEntry,
signal?: AbortSignal,
): Promise<string> => {
if (entry.declaredSize === null || entry.declaredSize > MAX_CATALOG_BYTES)
@@ -1,27 +1,25 @@
import { createHash } from "node:crypto";
import { parseBinary } from "plist";
import { DirectoryArtifactReader } from "../artifacts/DirectoryArtifactReader.js";
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
import { projectPlistValue } from "../../domain/apple/plistValue.js";
import {
omittedPrototypeKeysLimitation,
parseXmlPropertyList,
} from "../domain/propertyListKeys.js";
import {
decodeNibArchive,
type NibArchiveDocument,
} from "../artifacts/NibArchive.js";
import type { ArtifactEntry } from "../artifacts/ArtifactReader.js";
} from "../../domain/propertyListKeys.js";
import { decodeNibArchive, type NibArchiveDocument } from "./NibArchive.js";
import type { ArtifactEntry } from "../ArtifactReader.js";
import {
buildInterfaceBuilderAnalysis,
interfaceBuilderLimitsSchema,
type InterfaceBuilderDocumentInput,
} from "../domain/interfaceBuilderGraph.js";
} from "../../domain/apple/interfaceBuilderGraph.js";
import {
mergeNibHierarchies,
projectNibViewHierarchy,
type NibHierarchyNode,
} from "./NibViewHierarchy.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { jsonValueSchema, type JsonValue } from "../../domain/jsonValue.js";
const MAX_DOCUMENT_BYTES = 64 * 1024 * 1024;
@@ -214,15 +212,17 @@ const projectNibArchive = (archive: NibArchiveDocument) => {
const object = byId.get(objectId);
if (object === undefined) return null;
const storedClass = object.class_name.replace(/\0+$/u, "");
return storedClass === "NSClassSwapper"
? (referencedString(object.values.NSClassName) ?? storedClass)
if (storedClass === "NSClassSwapper")
return referencedString(object.values.NSClassName) ?? storedClass;
return storedClass === "UIClassSwapper"
? (referencedString(object.values.UIClassName) ?? storedClass)
: storedClass;
};
const objects = Object.fromEntries(
archive.objects
.filter((object) => {
const name = runtimeClass(object.id) ?? "";
return !/^(?:NSObject|NSIBObjectData|NSString|NSMutableString|NSNumber|NSArray|NSMutableArray|NSSet|NSMutableSet|NSDictionary|NSMutableDictionary|NSApplication|NSNib.*Connector)$/u.test(
return !/^(?:NSObject|NSIBObjectData|NSString|NSMutableString|NSNumber|NSArray|NSMutableArray|NSSet|NSMutableSet|NSDictionary|NSMutableDictionary|NSApplication|NSNib.*Connector|UIRuntime\w*Connection)$/u.test(
name,
);
})
@@ -268,26 +268,34 @@ const projectNibArchive = (archive: NibArchiveDocument) => {
};
for (const object of archive.objects) {
const className = object.class_name.replace(/\0+$/u, "");
const source = reference(object.values.NSSource);
const destination = reference(object.values.NSDestination);
if (className.includes("Connector") && source !== null) {
const label = referencedString(object.values.NSLabel);
const type = className.includes("Outlet")
? "outlet"
: className.includes("Control")
? "action"
: className;
// NSSource is the outlet owner or the sending control; NSDestination is
// the outlet value or the action target, and a nil target is the first
// responder.
(connections[String(source)] ??= []).push({
type,
"destination-id": destination === null ? null : String(destination),
label,
source_id: String(source),
archive_object_id: String(object.id),
});
}
// AppKit connectors use NS-prefixed keys; UIKit's runtime outlet and
// event connections use UI-prefixed keys with the same roles.
const uiKit = /^UIRuntime\w*Connection$/u.test(className);
if (!uiKit && !className.includes("Connector")) continue;
const values = object.values;
const source = reference(uiKit ? values.UISource : values.NSSource);
if (source === null) continue;
const destination = reference(
uiKit ? values.UIDestination : values.NSDestination,
);
const label = referencedString(uiKit ? values.UILabel : values.NSLabel);
const type = className.includes("Outlet")
? "outlet"
: className.includes("Control") || className.includes("Event")
? "action"
: className;
const eventMask = values.UIEventMask;
// The source is the outlet owner or the sending control; the destination
// is the outlet value or the action target, and a nil target is the
// first responder.
(connections[String(source)] ??= []).push({
type,
"destination-id": destination === null ? null : String(destination),
label,
source_id: String(source),
archive_object_id: String(object.id),
...(typeof eventMask === "number" ? { ui_event_mask: eventMask } : {}),
});
}
let hierarchyOmitted = 0;
const hierarchyFor = (
@@ -390,6 +398,7 @@ const readEntry = async (
return Buffer.concat(chunks, length);
};
/** Project decoded plist data and dates while retaining omitted-key coverage. */
const decodePlist = (
bytes: Buffer,
): { readonly value: JsonValue; readonly omittedPrototypeKeys: number } => {
@@ -397,5 +406,5 @@ const decodePlist = (
bytes.subarray(0, 8).toString("ascii") === "bplist00"
? { value: parseBinary(bytes), omittedPrototypeKeys: 0 }
: parseXmlPropertyList(bytes.toString("utf8"));
return { value: jsonValueSchema.parse(value), omittedPrototypeKeys };
return { value: projectPlistValue(value).value, omittedPrototypeKeys };
};
@@ -2,19 +2,19 @@ import { createHash } from "node:crypto";
import { TextDecoder } from "node:util";
import { parseBinary } from "plist";
import { z } from "zod";
import type { JsonValue } from "../domain/jsonValue.js";
import { projectPlistValue } from "../domain/plistValue.js";
import type { JsonValue } from "../../domain/jsonValue.js";
import { projectPlistValue } from "../../domain/apple/plistValue.js";
import {
omittedPrototypeKeysLimitation,
parseXmlPropertyList,
} from "../domain/propertyListKeys.js";
} from "../../domain/propertyListKeys.js";
import {
keyedArchiveInputSchema,
keyedArchiveResultSchema,
projectKeyedArchive,
} from "../domain/keyedArchive.js";
import { DirectoryArtifactReader } from "./DirectoryArtifactReader.js";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
} from "../../domain/apple/keyedArchive.js";
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
import { ArtifactReaderFailure } from "../ArtifactReader.js";
const MAX_BYTES = 64 * 1024 * 1024;
@@ -1,4 +1,4 @@
import type { JsonValue } from "../domain/jsonValue.js";
import type { JsonValue } from "../../domain/jsonValue.js";
import { TextDecoder } from "node:util";
const MAGIC = Buffer.from("NIBArchive", "ascii");
@@ -1,5 +1,5 @@
import type { NibArchiveDocument } from "../artifacts/NibArchive.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { NibArchiveDocument } from "./NibArchive.js";
import type { JsonValue } from "../../domain/jsonValue.js";
export type NibHierarchyNode = {
objectID: string;
+3 -3
View File
@@ -2,7 +2,7 @@ import { reconstructionCoverageEvaluationInputSchema } from "../domain/reconstru
import { Cli, z } from "incur";
import { projectAndroidApplicationEvidence } from "../application/android/AndroidApplicationService.js";
import { projectAppleApplicationEvidence } from "../application/AppleApplicationService.js";
import { projectAppleApplicationEvidence } from "../application/apple/AppleApplicationService.js";
import {
compareApplicationVersionsEvidenceValidated,
compareJavaScriptExportShapesEvidenceValidated,
@@ -19,7 +19,7 @@ import { AnalysisInputError } from "../domain/analysisErrorCore.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { type AnalysisError } from "../domain/analysisErrorBase.js";
import { androidApplicationProjectionInputSchema } from "../domain/android/androidApplication.js";
import { appleApplicationProjectionInputSchema } from "../domain/appleApplication.js";
import { appleApplicationProjectionInputSchema } from "../domain/apple/appleApplication.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import type { Logger } from "../logger.js";
import { traceApplicationFeatureInputSchema } from "../domain/javascript/javascriptFeatureTraceSchemas.js";
@@ -103,7 +103,7 @@ export const registerApplicationCommands = (
logger,
name: CLI_COMMANDS.projectAppleApplicationGraph,
description:
"Project authenticated IPA inventory Evidence into an Apple application graph",
"Project authenticated IPA or macOS app inventory Evidence into an Apple application graph",
inputSchema: appleApplicationProjectionInputSchema,
workflow: (input) => {
const result = projectAppleApplicationEvidence(input);
+3 -3
View File
@@ -1,8 +1,8 @@
import { z } from "incur";
import { compareManagedMemberPaths } from "../application/ManagedMemberComparisonService.js";
import { verifyManagedNativeBoundariesEvidence } from "../application/ManagedNativeVerificationService.js";
import { importManagedReconstructionEvidence } from "../application/ManagedReconstructionService.js";
import { compareManagedMemberPaths } from "../application/managed/ManagedMemberComparisonService.js";
import { verifyManagedNativeBoundariesEvidence } from "../application/managed/ManagedNativeVerificationService.js";
import { importManagedReconstructionEvidence } from "../application/managed/ManagedReconstructionService.js";
import { runProviderAnalysis } from "../application/DirectAnalysis.js";
import { parseCliJsonInput } from "../cliJsonInput.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
+1 -1
View File
@@ -1,6 +1,6 @@
import { z } from "incur";
import { projectManagedApplicationGraphEvidence } from "../application/ManagedApplicationGraphService.js";
import { projectManagedApplicationGraphEvidence } from "../application/managed/ManagedApplicationGraphService.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { parseCliJsonInput } from "../cliJsonInput.js";
import { logCliCommand } from "../cliLogging.js";
+8 -2
View File
@@ -23,7 +23,7 @@ import {
import {
appleApplicationProjectionInputSchema,
appleApplicationProjectionResultSchema,
} from "../domain/appleApplication.js";
} from "../domain/apple/appleApplication.js";
import type { ToolContract } from "./toolContracts.js";
import { toolContractMetadata } from "./toolEffects.js";
import { evidenceResultOf } from "./toolOutputSchemas.js";
@@ -36,6 +36,7 @@ import {
import {
ANDROID_APPLICATION_GRAPH_EXAMPLE,
APPLE_APPLICATION_GRAPH_EXAMPLE,
MACOS_APPLICATION_GRAPH_EXAMPLE,
} from "./mobileApplicationGraphExamples.js";
const traceOutputSchema = evidenceResultOf(applicationFeatureTraceResultSchema);
@@ -278,7 +279,7 @@ export const APPLICATION_TOOL_CONTRACTS = [
name: "project_apple_application_graph",
...toolContractMetadata("project_apple_application_graph"),
description:
"Project authenticated IPA inventory_artifact Evidence into an execution-free Apple application inventory. Reports exact component paths and hashes, runtime-family hints, and path-based bridge hypotheses without parsing plist/CMS semantics or claiming observed runtime calls.",
"Project authenticated IPA, macOS .app directory, ZIP, or DMG inventory Evidence into an execution-free Apple application inventory. Reports application roots, nested bundles with path-convention roles (app extensions, XPC services, login items, privileged helpers, system extensions, frameworks), launchd plists, exact component paths and hashes, runtime-family hints, and path-based bridge hypotheses without parsing plist/CMS semantics or claiming observed runtime calls.",
kind: "application",
inputSchema: appleApplicationProjectionInputSchema,
outputSchema: evidenceResultOf(appleApplicationProjectionResultSchema),
@@ -287,6 +288,11 @@ export const APPLICATION_TOOL_CONTRACTS = [
title: "Project IPA inventory Evidence into an Apple application graph",
input: APPLE_APPLICATION_GRAPH_EXAMPLE,
},
{
title:
"Project a macOS .app directory inventory into its bundle anatomy",
input: MACOS_APPLICATION_GRAPH_EXAMPLE,
},
],
},
] as const satisfies readonly ToolContract[];
+2 -2
View File
@@ -5,8 +5,8 @@ import { artifactOutputSchemas } from "./toolOutputSchemas.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { toolContractMetadata } from "./toolEffects.js";
import { requireOutputSchema } from "./toolOutputSchemaPrimitives.js";
import { appleAssetCatalogInputSchema } from "../domain/appleAssetCatalog.js";
import { keyedArchiveInputSchema } from "../domain/keyedArchive.js";
import { appleAssetCatalogInputSchema } from "../domain/apple/appleAssetCatalog.js";
import { keyedArchiveInputSchema } from "../domain/apple/keyedArchive.js";
import { artifactIntegrityPolicySchema } from "../domain/artifactGraph.js";
/** Exact caller boundary for deterministic artifact inventory. */
export const artifactInventoryInputSchema = z.strictObject({
+2 -2
View File
@@ -8,8 +8,8 @@ import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
import { FIRMWARE_TOOL_CONTRACTS } from "./firmware/firmwareToolContracts.js";
import { ANDROID_TOOL_CONTRACTS } from "./android/androidToolContracts.js";
import { MANAGED_TOOL_CONTRACTS } from "./managedToolContracts.js";
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managedWorkflowToolContracts.js";
import { MANAGED_TOOL_CONTRACTS } from "./managed/managedToolContracts.js";
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managed/managedWorkflowToolContracts.js";
import { BROWSER_TOOL_CONTRACTS } from "./browserToolContracts.js";
import { BROWSER_SCENARIO_TOOL_CONTRACTS } from "./browserScenarioToolContracts.js";
import { ELECTRON_TOOL_CONTRACTS } from "./javascript/electronToolContracts.js";
@@ -1,9 +1,9 @@
import { z } from "zod";
import type { ToolContract } from "./toolContracts.js";
import { managedOutputSchemas } from "./toolOutputSchemas.js";
import { toolContractMetadata } from "./toolEffects.js";
import { requireOutputSchema } from "./toolOutputSchemaPrimitives.js";
import type { ToolContract } from "../toolContracts.js";
import { managedOutputSchemas } from "../toolOutputSchemas.js";
import { toolContractMetadata } from "../toolEffects.js";
import { requireOutputSchema } from "../toolOutputSchemaPrimitives.js";
/** Exact caller boundary for execution-free PE/CLI triage and identity. */
const managedTargetInputSchema = z.object({
@@ -1,9 +1,9 @@
import { createEvidence } from "../domain/evidence.js";
import { createEvidence } from "../../domain/evidence.js";
import type {
ManagedMemberInspection,
ManagedNativeBoundaryInspection,
} from "../domain/managedArtifact.js";
import type { InspectMacho } from "../domain/nativeInspection.js";
} from "../../domain/managed/managedArtifact.js";
import type { InspectMacho } from "../../domain/nativeInspection.js";
const MANAGED_STATIC_EXAMPLE_PROVIDER = {
id: "rea-dotnet-static",
@@ -1,17 +1,17 @@
import { z } from "zod";
import { evidenceSchema } from "../domain/evidence.js";
import { evidenceSchema } from "../../domain/evidence.js";
import { managedReconstructionImportInputSchema } from "../domain/managedReconstruction.js";
import type { ToolContract } from "./toolContracts.js";
import { managedWorkflowOutputSchemas } from "./toolOutputSchemas.js";
import { managedReconstructionImportInputSchema } from "../../domain/managed/managedReconstruction.js";
import type { ToolContract } from "../toolContracts.js";
import { managedWorkflowOutputSchemas } from "../toolOutputSchemas.js";
import {
MANAGED_MEMBER_COMPARISON_EXAMPLE,
MANAGED_NATIVE_VERIFICATION_EXAMPLE,
MANAGED_APPLICATION_GRAPH_EXAMPLE,
MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE,
} from "./managedWorkflowExamples.js";
import { toolContractMetadata } from "./toolEffects.js";
import { requireOutputSchema } from "./toolOutputSchemaPrimitives.js";
import { toolContractMetadata } from "../toolEffects.js";
import { requireOutputSchema } from "../toolOutputSchemaPrimitives.js";
/** Inputs for comparing two managed observations carried inline. */
export const compareManagedMembersReferenceInputSchema = z
@@ -2,7 +2,7 @@ import { canonicalDigest } from "../domain/comparisonSemantics.js";
import { createEvidence } from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
const inventory = (format: "apk" | "ipa", digit: string) => {
const inventory = (format: "apk" | "ipa" | "directory", digit: string) => {
const sha = digit.repeat(64);
const artifactId = `art_${canonicalDigest({ sha256: sha }, "Artifact inventory")}`;
const occurrenceId = `occ_${canonicalDigest(
@@ -112,3 +112,20 @@ export const APPLE_APPLICATION_GRAPH_EXAMPLE = {
),
],
};
/** Catalog example for a macOS application bundle inventoried as a directory. */
export const MACOS_APPLICATION_GRAPH_EXAMPLE = {
inventory_evidence: [
createEvidence(
{ path: "Fixture.app", sha256: "c".repeat(64), format: "directory" },
provider,
{
operation: "inventory_artifact",
parameters: {},
result: inventory("directory", "c"),
confidence: "observed",
authority: "shipped-artifact",
},
),
],
};
+1 -1
View File
@@ -80,7 +80,7 @@ export const SESSION_TOOL_CONTRACTS = [
),
session(
"capture_process_scenario",
"Run one caller-selected command under a PTY and return process capture Evidence with residual unknowns. A command name resolves through the inherited PATH; the working directory defaults to the caller's current directory; host environment variables are inherited with scenario overrides. Filesystem snapshots are opt-in through filesystem_observation_paths. The target runs with the current user's permissions; this is not a security sandbox.",
"Run one caller-selected command under a PTY and return process capture Evidence with residual unknowns. A command name resolves through the inherited PATH; the working directory defaults to the caller's current directory; host environment variables are inherited with scenario overrides. Environment keys cannot contain '=' or NUL, and REA_PROCESS_RUN_ID is reserved for process ownership. Filesystem snapshots are opt-in through filesystem_observation_paths. The target runs with the current user's permissions; this is not a security sandbox.",
processScenarioSchema,
),
session(
+2 -2
View File
@@ -5,10 +5,10 @@ import { OFFICIAL_TOOL_CONTRACTS } from "./officialToolContracts.js";
import { SESSION_TOOL_CONTRACTS } from "./sessionToolContracts.js";
import { TOOL_CONTRACTS } from "./toolContracts.js";
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
import { MANAGED_TOOL_CONTRACTS } from "./managedToolContracts.js";
import { MANAGED_TOOL_CONTRACTS } from "./managed/managedToolContracts.js";
import { FIRMWARE_TOOL_CONTRACTS } from "./firmware/firmwareToolContracts.js";
import { ANDROID_TOOL_CONTRACTS } from "./android/androidToolContracts.js";
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managedWorkflowToolContracts.js";
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managed/managedWorkflowToolContracts.js";
import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
import { BROWSER_PROVIDER_TOOL_CONTRACTS } from "./browserProviderToolContracts.js";
import { ELECTRON_TOOL_CONTRACTS } from "./javascript/electronToolContracts.js";
+2 -2
View File
@@ -1,9 +1,9 @@
import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
import { MANAGED_TOOL_CONTRACTS } from "./managedToolContracts.js";
import { MANAGED_TOOL_CONTRACTS } from "./managed/managedToolContracts.js";
import { FIRMWARE_TOOL_CONTRACTS } from "./firmware/firmwareToolContracts.js";
import { ANDROID_TOOL_CONTRACTS } from "./android/androidToolContracts.js";
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managedWorkflowToolContracts.js";
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managed/managedWorkflowToolContracts.js";
import { BROWSER_PROVIDER_TOOL_CONTRACTS } from "./browserProviderToolContracts.js";
import { ELECTRON_TOOL_CONTRACTS } from "./javascript/electronToolContracts.js";
import { JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS } from "./javascript/javascriptRuntimeObservationToolContracts.js";
+8 -8
View File
@@ -30,18 +30,18 @@ import {
} from "../domain/nativeInspection.js";
import { artifactExtractionResultSchema } from "../domain/artifactGraph.js";
import { artifactInspectionResultSchema } from "../domain/artifactInspection.js";
import { interfaceBuilderAnalysisSchema } from "../domain/interfaceBuilderGraph.js";
import { keyedArchiveResultSchema } from "../domain/keyedArchive.js";
import { appleAssetCatalogResultSchema } from "../domain/appleAssetCatalog.js";
import { interfaceBuilderAnalysisSchema } from "../domain/apple/interfaceBuilderGraph.js";
import { keyedArchiveResultSchema } from "../domain/apple/keyedArchive.js";
import { appleAssetCatalogResultSchema } from "../domain/apple/appleAssetCatalog.js";
import {
managedArtifactInspectionSchema,
managedMemberInspectionSchema,
managedNativeBoundaryInspectionSchema,
} from "../domain/managedArtifact.js";
import { managedMemberComparisonResultSchema } from "../domain/managedMemberComparison.js";
import { managedNativeVerificationResultSchema } from "../domain/managedNativeVerification.js";
import { managedReconstructionImportResultSchema } from "../domain/managedReconstruction.js";
import { managedApplicationGraphResultSchema } from "../domain/managedApplicationGraph.js";
} from "../domain/managed/managedArtifact.js";
import { managedMemberComparisonResultSchema } from "../domain/managed/managedMemberComparison.js";
import { managedNativeVerificationResultSchema } from "../domain/managed/managedNativeVerification.js";
import { managedReconstructionImportResultSchema } from "../domain/managed/managedReconstruction.js";
import { managedApplicationGraphResultSchema } from "../domain/managed/managedApplicationGraph.js";
import { artifactComparisonResultSchema } from "../domain/artifactComparison.js";
import { functionComparisonResultSchema } from "../domain/functionComparison.js";
import { bundleComparisonResultSchema } from "../domain/bundleComparison.js";
+2 -2
View File
@@ -7,12 +7,12 @@ import {
MANAGED_APPLICATION_GRAPH_EXAMPLE,
MANAGED_MEMBER_COMPARISON_EXAMPLE,
MANAGED_NATIVE_VERIFICATION_EXAMPLE,
} from "./managedWorkflowExamples.js";
} from "./managed/managedWorkflowExamples.js";
import {
compareManagedMembersReferenceInputSchema,
managedApplicationGraphReferenceInputSchema,
managedNativeVerificationReferenceInputSchema,
} from "./managedWorkflowToolContracts.js";
} from "./managed/managedWorkflowToolContracts.js";
describe("workflow input contracts", () => {
it("rejects application Evidence ID references and duplicate inline records", () => {
+497
View File
@@ -0,0 +1,497 @@
import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import { projectAppleApplication } from "./appleApplication.js";
import { canonicalDigest } from "../comparisonSemantics.js";
import { createEvidence, type Evidence } from "../evidence.js";
import { jsonValueSchema } from "../jsonValue.js";
type EntryKind = "file" | "directory" | "symlink";
type RootFormat = "ipa" | "zip" | "dmg" | "directory" | "asar";
interface FixtureEntry {
readonly path: string;
readonly kind?: EntryKind;
readonly format?: string;
}
const sha = (text: string): string =>
createHash("sha256").update(text).digest("hex");
const artifactId = (sha256: string): string =>
`art_${canonicalDigest({ sha256 }, "Artifact inventory")}`;
/** Build one complete, content-addressed inventory page for pure projection tests. */
const inventoryEvidence = (
rootFormat: RootFormat,
subjectName: string,
entries: readonly FixtureEntry[],
): Evidence => {
const rootSha = sha(`${rootFormat}:${subjectName}`);
const rootId = artifactId(rootSha);
const node = (sha256: string, format: string) => ({
artifact_id: artifactId(sha256),
kind: "resource",
format,
sha256,
size: 1,
media_type: null,
architecture: null,
executable: false,
content_state: "materialized",
limitations: [],
});
const occurrence = (path: string, kind: EntryKind, id: string | null) => ({
occurrence_id:
path === "."
? `occ_${canonicalDigest({ root: rootId }, "Artifact inventory")}`
: `occ_${canonicalDigest(
{ root_artifact_id: rootId, logical_path: path, entry_kind: kind },
"Artifact inventory",
)}`,
artifact_id: id,
parent_occurrence_id: null,
logical_path: path,
entry_kind: kind,
declared_size: null,
compressed_size: null,
executable: false,
encrypted: false,
hash_status: "verified",
source_location: null,
limitations: [],
});
const nodes = new Map([[rootId, node(rootSha, rootFormat)]]);
const occurrences = [occurrence(".", "file", rootId)];
for (const { path, kind = "file", format = "file" } of entries) {
if (kind === "symlink") {
occurrences.push(occurrence(path, kind, null));
continue;
}
const contentSha = sha(`${kind}:${path}`);
const id = artifactId(contentSha);
nodes.set(
id,
node(contentSha, kind === "directory" ? "directory" : format),
);
occurrences.push(occurrence(path, kind, id));
}
const sortedNodes = [...nodes.values()].sort((left, right) =>
left.artifact_id.localeCompare(right.artifact_id),
);
const sortedOccurrences = occurrences.sort((left, right) =>
left.logical_path.localeCompare(right.logical_path, "en"),
);
const graphSha256 = canonicalDigest(
{
nodes: sortedNodes,
occurrences: sortedOccurrences,
edges: [],
integrity_contradictions: [],
},
"Artifact inventory",
);
return createEvidence(
{
path: `/fixtures/${subjectName}`,
sha256: rootSha,
format: rootFormat,
},
{ id: "rea-artifact-graph", name: "fixture", version: "1" },
{
operation: "inventory_artifact",
parameters: {},
confidence: "observed",
authority: "shipped-artifact",
result: jsonValueSchema.parse({
manifest: {
manifest_id: `agm_${canonicalDigest(
{ root_artifact_id: rootId, graph_sha256: graphSha256 },
"Artifact inventory",
)}`,
root_artifact_id: rootId,
root_sha256: rootSha,
root_format: rootFormat,
graph_sha256: graphSha256,
node_count: sortedNodes.length,
occurrence_count: sortedOccurrences.length,
edge_count: 0,
},
nodes: sortedNodes,
occurrences: sortedOccurrences,
edges: [],
provenance: [],
limitations: [],
}),
},
);
};
const project = (evidence: Evidence) =>
projectAppleApplication({ inventory_evidence: [evidence] });
const macho = (path: string): FixtureEntry => ({ path, format: "mach-o" });
describe("macOS application roots and bundle roles", () => {
it("treats an inventoried .app directory as its own application root", () => {
const result = project(
inventoryEvidence("directory", "Fixture.app", [
{ path: "Contents/Info.plist" },
macho("Contents/MacOS/Fixture"),
{ path: "Contents/_CodeSignature/CodeResources" },
{ path: "Contents/embedded.provisionprofile" },
macho("Contents/Library/LaunchServices/com.example.helper"),
{ path: "Contents/Library/LaunchDaemons/com.example.helper.plist" },
{ path: "Contents/Library/LaunchAgents/com.example.agent.plist" },
macho("Contents/Helpers/tool"),
macho("Contents/Helpers/Assistant.app/Contents/MacOS/Assistant"),
macho(
"Contents/Library/SystemExtensions/com.example.filter.systemextension/Contents/MacOS/com.example.filter",
),
macho(
"Contents/Library/SystemExtensions/com.example.driver.dext/driver",
),
{ path: "Contents/PlugIns/Preview.qlgenerator", kind: "directory" },
macho("Contents/PlugIns/Bridge.bundle/Contents/MacOS/Bridge"),
{ path: "Contents/Resources/Strings.bundle/Info.plist" },
{ path: "Contents/SharedSupport/Data.bundle", kind: "directory" },
macho("Contents/Resources/Embedded.app/Contents/MacOS/Embedded"),
]),
);
expect(result).toMatchObject({
root_format: "directory",
platforms: ["macos"],
application_roots: ["."],
});
expect(
result.bundles.map(({ path, role, layout, parent_path: parent }) => ({
path,
role,
layout,
parent,
})),
).toEqual([
{ path: ".", role: "application", layout: "macos-deep", parent: null },
{
path: "Contents/Helpers/Assistant.app",
role: "helper-application",
layout: "macos-deep",
parent: ".",
},
{
path: "Contents/Library/SystemExtensions/com.example.driver.dext",
role: "driver-extension",
layout: "shallow",
parent: ".",
},
{
path: "Contents/Library/SystemExtensions/com.example.filter.systemextension",
role: "system-extension",
layout: "macos-deep",
parent: ".",
},
{
path: "Contents/PlugIns/Bridge.bundle",
role: "plug-in",
layout: "macos-deep",
parent: ".",
},
{
path: "Contents/PlugIns/Preview.qlgenerator",
role: "plug-in",
layout: "shallow",
parent: ".",
},
{
path: "Contents/Resources/Embedded.app",
role: "nested-application",
layout: "macos-deep",
parent: ".",
},
{
path: "Contents/Resources/Strings.bundle",
role: "resource-bundle",
layout: "shallow",
parent: ".",
},
{
path: "Contents/SharedSupport/Data.bundle",
role: "bundle",
layout: "shallow",
parent: ".",
},
]);
expect(result.bundles[0]).toMatchObject({
info_plist_path: "Contents/Info.plist",
executable_candidates: ["Contents/MacOS/Fixture"],
signing_paths: [
"Contents/_CodeSignature/CodeResources",
"Contents/embedded.provisionprofile",
],
});
expect(
result.components.privileged_helpers.map(({ path }) => path),
).toEqual(["Contents/Library/LaunchServices/com.example.helper"]);
expect(
result.components.launchd_plists.map(({ path, domain }) => [
path,
domain,
]),
).toEqual([
["Contents/Library/LaunchAgents/com.example.agent.plist", "agent"],
["Contents/Library/LaunchDaemons/com.example.helper.plist", "daemon"],
]);
expect(result.components.helpers.map(({ path }) => path)).toEqual([
"Contents/Helpers/tool",
]);
});
it("does not make a non-application bundle directory an application root", () => {
const result = project(
inventoryEvidence("directory", "Service.xpc", [
{ path: "Contents/Info.plist" },
macho("Contents/MacOS/Service"),
]),
);
expect(result.application_roots).toEqual([]);
expect(result.bundles).toEqual([]);
expect(result.limitations).toContain(
"No application bundle (Payload/*.app or *.app/Contents) was present in the supplied inventory pages.",
);
});
});
describe("Apple bundle layouts and containers", () => {
it("follows versioned frameworks without resolving Versions/Current", () => {
const framework = "Fixture.app/Contents/Frameworks/Core.framework";
const result = project(
inventoryEvidence("zip", "Fixture.zip", [
macho("Fixture.app/Contents/MacOS/Fixture"),
{ path: `${framework}/Core`, kind: "symlink" },
{ path: `${framework}/Versions/Current`, kind: "symlink" },
macho(`${framework}/Versions/A/Core`),
{ path: `${framework}/Versions/A/Resources/Info.plist` },
{ path: `${framework}/Versions/A/_CodeSignature/CodeResources` },
macho(
`${framework}/Versions/A/XPCServices/Fetch.xpc/Contents/MacOS/Fetch`,
),
]),
);
const core = result.bundles.find(({ path }) => path === framework);
expect(core).toEqual({
path: framework,
parent_path: "Fixture.app",
layout: "versioned-framework",
role: "framework",
role_basis: "path-convention",
info_plist_path: `${framework}/Versions/A/Resources/Info.plist`,
executable_candidates: [`${framework}/Versions/A/Core`],
signing_paths: [`${framework}/Versions/A/_CodeSignature/CodeResources`],
});
expect(
result.bundles.find(({ role }) => role === "xpc-service")?.parent_path,
).toBe(framework);
expect(result.symlinks).toEqual([
`${framework}/Core`,
`${framework}/Versions/Current`,
]);
});
it("reports an unknown Info.plist when several framework versions exist", () => {
const framework = "Fixture.app/Contents/Frameworks/Core.framework";
const result = project(
inventoryEvidence("zip", "Fixture.zip", [
macho("Fixture.app/Contents/MacOS/Fixture"),
{ path: `${framework}/Versions/A/Resources/Info.plist` },
{ path: `${framework}/Versions/B/Resources/Info.plist` },
]),
);
expect(
result.bundles.find(({ path }) => path === framework)?.info_plist_path,
).toBeNull();
// Files beside the only real version are not versions.
const withFiles = project(
inventoryEvidence("zip", "Fixture.zip", [
macho("Fixture.app/Contents/MacOS/Fixture"),
{ path: `${framework}/Versions/A/Resources/Info.plist` },
{ path: `${framework}/Versions/.DS_Store` },
{ path: `${framework}/Versions/Current`, kind: "symlink" },
]),
);
expect(
withFiles.bundles.find(({ path }) => path === framework)?.info_plist_path,
).toBe(`${framework}/Versions/A/Resources/Info.plist`);
// Only A has a plist, but Versions/Current may select B.
const onlyA = project(
inventoryEvidence("zip", "Fixture.zip", [
macho("Fixture.app/Contents/MacOS/Fixture"),
{ path: `${framework}/Versions/A/Resources/Info.plist` },
macho(`${framework}/Versions/B/Core`),
]),
);
expect(
onlyA.bundles.find(({ path }) => path === framework)?.info_plist_path,
).toBeNull();
expect(result.limitations).toContainEqual(
expect.stringContaining("Versions/Current selects is unknown"),
);
});
it("excludes AppleDouble sidecars from roots and roles", () => {
const result = project(
inventoryEvidence("zip", "Fixture.zip", [
macho("Fixture.app/Contents/MacOS/Fixture"),
{ path: "Fixture.app/Contents/Library/LaunchDaemons/._helper.plist" },
{ path: "Fixture.app/Contents/Library/LaunchDaemons/helper.plist" },
{ path: "__MACOSX/Other.app/Contents/._Info.plist" },
]),
);
expect(result.application_roots).toEqual(["Fixture.app"]);
expect(result.components.launchd_plists.map(({ path }) => path)).toEqual([
"Fixture.app/Contents/Library/LaunchDaemons/helper.plist",
]);
expect(result.limitations).toContainEqual(
expect.stringContaining("AppleDouble sidecar entries"),
);
});
it("reports a DMG without inventoried contents as partial", () => {
const result = project(inventoryEvidence("dmg", "Fixture.dmg", []));
expect(result.coverage).toEqual({
status: "partial",
inventory_complete: true,
});
expect(result.limitations).toContain(
"The DMG's contents were not inventoried on this host; bundle absence is unknown.",
);
});
it("keeps IPA applications shallow and iOS", () => {
const result = project(
inventoryEvidence("ipa", "Fixture.ipa", [
{ path: "Payload/Fixture.app/Info.plist" },
macho("Payload/Fixture.app/Fixture"),
{ path: "Payload/Fixture.app/embedded.mobileprovision" },
macho("Payload/Fixture.app/PlugIns/Share.appex/Share"),
macho("SwiftSupport/iphoneos/libswiftCore.dylib"),
]),
);
expect(result.platforms).toEqual(["ios"]);
// IPA projection still lists archive components outside Payload/.
expect(result.components.native_libraries.map(({ path }) => path)).toEqual([
"SwiftSupport/iphoneos/libswiftCore.dylib",
]);
expect(
result.bundles.map(({ path, role, layout }) => [path, role, layout]),
).toEqual([
["Payload/Fixture.app", "application", "shallow"],
["Payload/Fixture.app/PlugIns/Share.appex", "app-extension", "shallow"],
]);
expect(result.bundles[0]?.executable_candidates).toEqual([
"Payload/Fixture.app/Fixture",
]);
});
it("rejects inventories that cannot contain an Apple application", () => {
expect(() => project(inventoryEvidence("asar", "app.asar", []))).toThrow(
"Apple application projection requires IPA, directory, ZIP, or DMG inventory Evidence (got asar)",
);
});
});
describe("macOS application scope", () => {
it("attributes only components inside the application roots", () => {
const result = project(
inventoryEvidence("zip", "Distribution.zip", [
macho("Fixture.app/Contents/MacOS/Fixture"),
macho("Fixture.app/Contents/Frameworks/Core.framework/Versions/A/Core"),
{
path: "Fixture.app/Contents/Resources/app.js",
format: "javascript-bundle",
},
macho("Extras/Plugin.framework/Versions/A/Plugin"),
macho("Extras/libextra.dylib"),
{ path: "Extras/installer.js", format: "javascript-bundle" },
{ path: "Extras/Info.plist" },
]),
);
const paths = (components: readonly { readonly path: string }[]) =>
components.map(({ path }) => path);
expect(paths(result.components.frameworks)).toEqual([
"Fixture.app/Contents/Frameworks/Core.framework/Versions/A/Core",
]);
expect(paths(result.components.native_libraries)).toEqual([]);
expect(paths(result.components.javascript)).toEqual([
"Fixture.app/Contents/Resources/app.js",
]);
expect(paths(result.components.bundle_metadata)).toEqual([]);
expect(
result.bridge_candidates.every(
({ source_path: source, native_path: target }) =>
[source, target].every((path) => path.startsWith("Fixture.app/")),
),
).toBe(true);
expect(result.limitations).toContain(
"4 inventoried entries outside every application root are not attributed to the application.",
);
});
it("keeps a selected .app directory as the root when its contents are missing", () => {
const empty = project(inventoryEvidence("directory", "Fixture.app", []));
expect(empty).toMatchObject({
application_roots: ["."],
platforms: [],
bundles: [
{
path: ".",
role: "application",
layout: "shallow",
info_plist_path: null,
},
],
});
const partial = project(
inventoryEvidence("directory", "Fixture.app", [
{ path: "Contents/Resources/Localizable.strings" },
]),
);
expect(partial).toMatchObject({
application_roots: ["."],
platforms: ["macos"],
});
});
});
describe("Apple application bridge candidates", () => {
it("pairs scripts and native code only within one application root", () => {
const result = project(
inventoryEvidence("zip", "Suite.zip", [
macho("First.app/Contents/MacOS/First"),
{
path: "First.app/Contents/Resources/first.js",
format: "javascript-bundle",
},
macho("Second.app/Contents/MacOS/Second"),
{
path: "Second.app/Contents/Resources/second.js",
format: "javascript-bundle",
},
]),
);
expect(result.application_roots).toEqual(["First.app", "Second.app"]);
expect(
result.bridge_candidates.map(
({ source_path: source, native_path: target }) => [source, target],
),
).toEqual([
[
"First.app/Contents/Resources/first.js",
"First.app/Contents/MacOS/First",
],
[
"Second.app/Contents/Resources/second.js",
"Second.app/Contents/MacOS/Second",
],
]);
});
});
+403
View File
@@ -0,0 +1,403 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import {
appleBundleSchema,
appleComponentSchema,
applicationRoots,
detectBundles,
isMachOFormat,
isSidecar,
isWithin,
platformsOf,
type AppleInventoryEntry,
} from "./appleBundleAnatomy.js";
import { parseArtifactInventoryEvidence } from "../artifactInventoryEvidence.js";
import { evidenceSchema } from "../evidence.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const pathSchema = z.string().min(1);
const APPLE_ROOT_FORMATS = ["ipa", "directory", "zip", "dmg"] as const;
/** Authenticated artifact inventory pages projected as one Apple application. */
export const appleApplicationProjectionInputSchema = z.strictObject({
inventory_evidence: z.array(evidenceSchema).min(1),
});
/** Deterministic, execution-free Apple application inventory projection. */
export const appleApplicationProjectionResultSchema = z.strictObject({
projection_id: prefixedDigestSchema("aap"),
root_sha256: digestSchema,
root_format: z.enum(APPLE_ROOT_FORMATS),
platforms: z.array(z.enum(["ios", "macos"])),
source_evidence_ids: z.array(evidenceIdSchema).min(1),
application_roots: z.array(pathSchema),
bundles: z.array(appleBundleSchema),
components: z.strictObject({
bundle_metadata: z.array(appleComponentSchema),
executables: z.array(appleComponentSchema),
frameworks: z.array(appleComponentSchema),
native_libraries: z.array(appleComponentSchema),
javascript: z.array(appleComponentSchema),
signing: z.array(appleComponentSchema),
privileged_helpers: z.array(appleComponentSchema),
launchd_plists: z.array(
appleComponentSchema.extend({ domain: z.enum(["agent", "daemon"]) }),
),
helpers: z.array(appleComponentSchema),
}),
symlinks: z.array(pathSchema),
runtime_families: z.array(
z.enum([
"native",
"swift-objective-c",
"javascript",
"react-native",
"flutter",
"unity",
]),
),
bridge_candidates: z.array(
z.strictObject({
source_path: pathSchema,
native_path: pathSchema,
basis: z.enum([
"javascript-and-native-content",
"react-native-convention",
"flutter-convention",
"unity-convention",
]),
}),
),
coverage: z.strictObject({
status: z.enum(["complete-within-inventory", "partial"]),
inventory_complete: z.boolean(),
}),
limitations: z.array(z.string().min(1)),
});
export type AppleApplicationProjectionInput = z.infer<
typeof appleApplicationProjectionInputSchema
>;
export type AppleApplicationProjectionResult = z.infer<
typeof appleApplicationProjectionResultSchema
>;
type Component = z.infer<typeof appleComponentSchema>;
type RootFormat = (typeof APPLE_ROOT_FORMATS)[number];
/** Project exact Apple application paths and hashes without parsing or executing target code. */
export const projectAppleApplication = (
input: AppleApplicationProjectionInput,
): AppleApplicationProjectionResult => {
const parsed = appleApplicationProjectionInputSchema.parse(input);
const { evidence, inventory } = parseArtifactInventoryEvidence(
parsed.inventory_evidence,
);
const rootFormat = appleRootFormat(inventory.manifest.root_format);
const nodes = new Map(
inventory.nodes.map((node) => [node.artifact_id, node]),
);
const entries: AppleInventoryEntry[] = inventory.occurrences
.filter(({ logical_path: path }) => path !== ".")
.map((occurrence) => {
if (occurrence.artifact_id === null)
return {
path: occurrence.logical_path,
kind: occurrence.entry_kind,
component: undefined,
};
const node = nodes.get(occurrence.artifact_id);
if (node === undefined)
throw new TypeError(
"Apple application occurrence has no artifact node",
);
return {
path: occurrence.logical_path,
kind: occurrence.entry_kind,
component: {
path: occurrence.logical_path,
artifact_id: node.artifact_id,
sha256: node.sha256,
format: node.format,
},
};
});
const inventoried = entries.flatMap(({ component }) =>
component === undefined ? [] : [component],
);
const roots = applicationRoots(entries, {
name: evidence[0]?.subject?.name ?? "",
format: rootFormat,
});
const { all, unattributed } = attributeComponents(
inventoried,
roots,
rootFormat,
);
const bundles = detectBundles(entries, roots);
const classified = classifyComponents(entries, all, roots);
const runtimeFamilies = identifyRuntimeFamilies(all);
const bridgeProjection = identifyBridgeCandidates(
classified.javascript,
deduplicateComponents([
...classified.executables,
...classified.native_libraries,
]),
roots,
);
const uninventoriedImage =
rootFormat === "dmg" && inventory.occurrences.length === 1;
const complete = inventory.complete && !uninventoriedImage;
const limitations = projectionLimitations({
complete: inventory.complete,
uninventoriedImage,
roots,
bundles,
sidecars: entries.some(({ path }) => isSidecar(path)),
symlinks: entries.some(({ kind }) => kind === "symlink"),
unattributed,
});
const withoutId = {
root_sha256: inventory.manifest.root_sha256,
root_format: rootFormat,
platforms: platformsOf(bundles),
source_evidence_ids: evidence
.map(({ evidence_id: id }) => id)
.sort(compare),
application_roots: roots,
bundles,
components: classified,
symlinks: entries
.filter(({ kind }) => kind === "symlink")
.map(({ path }) => path)
.sort(compare),
runtime_families: runtimeFamilies,
bridge_candidates: bridgeProjection.candidates,
coverage: {
status: complete
? ("complete-within-inventory" as const)
: ("partial" as const),
inventory_complete: inventory.complete,
},
limitations,
};
return appleApplicationProjectionResultSchema.parse({
...withoutId,
projection_id: `aap_${digest(withoutId)}`,
});
};
/**
* IPA projection keeps every archive component, as before. Directory, ZIP,
* and DMG inventories can hold installers and other siblings, so only
* components inside an application root are attributed to it.
*/
const attributeComponents = (
inventoried: readonly Component[],
roots: readonly string[],
rootFormat: RootFormat,
): { readonly all: Component[]; readonly unattributed: number } => {
if (rootFormat === "ipa") return { all: [...inventoried], unattributed: 0 };
const visible = inventoried.filter(({ path }) => !isSidecar(path));
const all = visible.filter(({ path }) =>
roots.some((root) => isWithin(path, root)),
);
return { all, unattributed: visible.length - all.length };
};
const appleRootFormat = (format: string): RootFormat => {
const root = APPLE_ROOT_FORMATS.find((candidate) => candidate === format);
if (root === undefined)
throw new TypeError(
`Apple application projection requires IPA, directory, ZIP, or DMG inventory Evidence (got ${format})`,
);
return root;
};
const classifyComponents = (
entries: readonly AppleInventoryEntry[],
all: readonly Component[],
roots: readonly string[],
) => {
const withinApp = (path: string): boolean =>
roots.some((root) => isWithin(path, root));
const anatomy = (pattern: RegExp): Component[] =>
entries.flatMap(({ path, kind, component }) =>
kind === "file" &&
component !== undefined &&
!isSidecar(path) &&
withinApp(path) &&
pattern.test(path)
? [component]
: [],
);
return {
bundle_metadata: all.filter(({ path }) =>
/(?:^|\/)Info\.plist$/u.test(path),
),
executables: all.filter(
({ path, format }) => withinApp(path) && isMachOFormat(format),
),
frameworks: all.filter(({ path }) => /\.framework\//u.test(path)),
native_libraries: all.filter(({ path }) => /\.(?:dylib|so)$/iu.test(path)),
javascript: all.filter(({ format }) => format === "javascript-bundle"),
signing: all.filter(({ path }) =>
/(?:^|\/)(?:embedded\.(?:mobileprovision|provisionprofile)|_CodeSignature\/CodeResources)$/u.test(
path,
),
),
privileged_helpers: anatomy(
/(?:^|\/)Contents\/Library\/LaunchServices\/[^/]+$/u,
),
launchd_plists: anatomy(
/(?:^|\/)Contents\/Library\/Launch(?:Agents|Daemons)\/[^/]+\.plist$/u,
).map((component) => ({
...component,
domain: component.path.includes("/LaunchDaemons/")
? ("daemon" as const)
: ("agent" as const),
})),
helpers: anatomy(/(?:^|\/)Contents\/Helpers\/[^/]+$/u),
};
};
const deduplicateComponents = (values: readonly Component[]): Component[] =>
[...new Map(values.map((value) => [value.path, value])).values()].sort(
(left, right) => compare(left.path, right.path),
);
const identifyRuntimeFamilies = (all: readonly Component[]) => {
const paths = all.map(({ path }) => path.toLowerCase());
const families = new Set<
z.infer<
typeof appleApplicationProjectionResultSchema
>["runtime_families"][number]
>();
if (all.some(({ format }) => ["mach-o", "mach-o-universal"].includes(format)))
families.add("native");
if (paths.some((path) => /\.(?:dylib|framework\/[^/]+)$/u.test(path)))
families.add("swift-objective-c");
if (all.some(({ format }) => format === "javascript-bundle"))
families.add("javascript");
if (
paths.some(
(path) =>
path.includes("reactnative") ||
path.includes("react.framework") ||
path.includes("hermes"),
)
)
families.add("react-native");
if (
paths.some(
(path) =>
path.includes("flutter.framework") || path.includes("app.framework"),
)
)
families.add("flutter");
if (paths.some((path) => path.includes("unityframework.framework")))
families.add("unity");
return [...families].sort(compare);
};
/** Pair scripts and native code only within the same application root. */
const identifyBridgeCandidates = (
scripts: readonly Component[],
native: readonly Component[],
roots: readonly string[],
) => {
const owner = (path: string): string | null =>
roots.find((root) => isWithin(path, root)) ?? null;
return {
candidates: scripts.flatMap((script) => {
const root = owner(script.path);
return native
.filter(({ path }) => owner(path) === root)
.map((item) => ({
source_path: script.path,
native_path: item.path,
basis: bridgeBasis(item.path),
}));
}),
};
};
const bridgeBasis = (
path: string,
):
| "javascript-and-native-content"
| "react-native-convention"
| "flutter-convention"
| "unity-convention" => {
const lower = path.toLowerCase();
if (lower.includes("react")) return "react-native-convention";
if (lower.includes("flutter") || lower.includes("app.framework"))
return "flutter-convention";
if (lower.includes("unity")) return "unity-convention";
return "javascript-and-native-content";
};
const projectionLimitations = (facts: {
readonly complete: boolean;
readonly uninventoriedImage: boolean;
readonly roots: readonly string[];
readonly bundles: readonly z.infer<typeof appleBundleSchema>[];
readonly sidecars: boolean;
readonly symlinks: boolean;
readonly unattributed: number;
}): string[] => [
...(!facts.complete
? ["Source inventory pages are incomplete; absence is unknown."]
: []),
...(facts.uninventoriedImage
? [
"The DMG's contents were not inventoried on this host; bundle absence is unknown.",
]
: []),
...(facts.roots.length === 0
? [
"No application bundle (Payload/*.app or *.app/Contents) was present in the supplied inventory pages.",
]
: []),
...(facts.bundles.some(
({ layout, info_plist_path: plist }) =>
layout === "versioned-framework" && plist === null,
)
? [
"A versioned framework has several version directories or no Versions/*/Resources/Info.plist; the Info.plist that Versions/Current selects is unknown because symlink targets are not inventoried.",
]
: []),
...(facts.symlinks
? [
"Symlinks are reported by path only; their targets are not inventoried, so bundles are reported at their real paths.",
]
: []),
...(facts.unattributed > 0
? [
`${facts.unattributed} inventoried entries outside every application root are not attributed to the application.`,
]
: []),
...(facts.sidecars
? [
"AppleDouble sidecar entries (._* files and __MACOSX/) describe neighbouring files and are excluded from bundle roles.",
]
: []),
"Bundle roles follow path conventions. Read each info_plist_path with inspect_plist for CFBundleExecutable, identifiers, and declared services.",
"Bundle identifiers and signing claims require dedicated plist and CMS parsing; this projection reports only exact paths and hashes.",
"Bridge candidates are path-based hypotheses, not observed runtime calls.",
];
const compare = (left: string, right: string): number =>
left < right ? -1 : left > right ? 1 : 0;
const digest = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError("Apple application projection is not canonical JSON");
return createHash("sha256").update(encoded).digest("hex");
};
@@ -1,7 +1,7 @@
import { z } from "zod";
import { jsonValueSchema } from "./jsonValue.js";
import { AnalysisOutputError } from "./analysisErrorCore.js";
import { jsonValueSchema } from "../jsonValue.js";
import { AnalysisOutputError } from "../analysisErrorCore.js";
/** Caller-controlled page bounds for compiled Apple asset metadata. */
export const appleAssetCatalogInputSchema = z.strictObject({
+307
View File
@@ -0,0 +1,307 @@
import { z } from "zod";
import { digestSchema, prefixedDigestSchema } from "../digests.js";
const pathSchema = z.string().min(1);
const BUNDLE_EXTENSION =
/\.(?:app|appex|xpc|framework|systemextension|dext|bundle|plugin|qlgenerator|mdimporter)$/iu;
const MACH_O_FORMATS: readonly string[] = ["mach-o", "mach-o-universal"];
/** One inventoried file or directory with its content identity. */
export const appleComponentSchema = z.strictObject({
path: pathSchema,
artifact_id: prefixedDigestSchema("art"),
sha256: digestSchema,
format: z.string().min(1),
});
/** One application root or nested bundle classified by path convention. */
export const appleBundleSchema = z.strictObject({
path: pathSchema,
parent_path: pathSchema.nullable(),
layout: z.enum(["shallow", "macos-deep", "versioned-framework"]),
role: z.enum([
"application",
"app-extension",
"xpc-service",
"framework",
"login-item",
"system-extension",
"driver-extension",
"plug-in",
"resource-bundle",
"bundle",
"helper-application",
"nested-application",
]),
role_basis: z.literal("path-convention"),
info_plist_path: pathSchema.nullable(),
executable_candidates: z.array(pathSchema),
signing_paths: z.array(pathSchema),
});
type Component = z.infer<typeof appleComponentSchema>;
type Bundle = z.infer<typeof appleBundleSchema>;
/** One inventory occurrence; symlinks and directories may lack content identity. */
export interface AppleInventoryEntry {
readonly path: string;
readonly kind: "file" | "directory" | "symlink" | "slice";
readonly component: Component | undefined;
}
type Entry = AppleInventoryEntry;
/** Report whether an inventory format is a thin or universal Mach-O. */
export const isMachOFormat = (format: string): boolean =>
MACH_O_FORMATS.includes(format);
/** AppleDouble metadata written beside archived files (`._name`, `__MACOSX/`). */
export const isSidecar = (path: string): boolean => {
const segments = path.split("/");
return (
segments.includes("__MACOSX") || (segments.at(-1) ?? "").startsWith("._")
);
};
export const isWithin = (path: string, root: string): boolean =>
root === "." || path === root || path.startsWith(`${root}/`);
/**
* Outermost iOS (`Payload/X.app`) and macOS (`X.app/Contents/…`) applications.
* An inventoried `.app` directory is its own root, `.`.
*/
export const applicationRoots = (
entries: readonly Entry[],
subject: { readonly name: string; readonly format: string },
): string[] => {
// A selected `.app` directory is the application, even when its inventory
// is partial or lacks Contents/; coverage and limitations describe that.
if (subject.format === "directory" && /\.app$/iu.test(subject.name))
return ["."];
const found = new Set<string>();
for (const { path } of entries) {
if (isSidecar(path)) continue;
const ios = /^(Payload\/[^/]+\.app)(?:\/|$)/u.exec(path);
if (ios?.[1] !== undefined) {
found.add(ios[1]);
continue;
}
const segments = path.split("/");
const index = segments.findIndex(
(segment, position) =>
/\.app$/iu.test(segment) && segments[position + 1] === "Contents",
);
if (index >= 0) found.add(segments.slice(0, index + 1).join("/"));
}
const roots = [...found];
return roots
.filter(
(root) => !roots.some((other) => other !== root && isWithin(root, other)),
)
.sort(compare);
};
export const detectBundles = (
entries: readonly Entry[],
roots: readonly string[],
): Bundle[] => {
const paths = new Set<string>(roots);
for (const { path, kind } of entries) {
if (isSidecar(path)) continue;
const root = roots.find((candidate) => isWithin(path, candidate));
if (root === undefined) continue;
const segments = path.split("/");
const start = root === "." ? 0 : root.split("/").length;
for (let index = start; index < segments.length; index++) {
const segment = segments[index] ?? "";
const leaf = index === segments.length - 1;
// A symlink or file named like a bundle has no observed contents.
if (BUNDLE_EXTENSION.test(segment) && (!leaf || kind === "directory"))
paths.add(segments.slice(0, index + 1).join("/"));
}
}
const tree = indexTree(entries);
return [...paths].sort(compare).map((path) => {
const layout = bundleLayout(path, tree);
return {
path,
parent_path: enclosingBundle(path, paths),
layout,
role: roots.includes(path) ? "application" : bundleRole(path),
role_basis: "path-convention",
info_plist_path: infoPlistPath(path, layout, tree),
executable_candidates: executableCandidates(path, layout, tree),
signing_paths: signingPaths(path, layout, tree),
} satisfies Bundle;
});
};
/** Directory children (including implied ancestors) and files, indexed once. */
interface Tree {
readonly children: ReadonlyMap<string, ReadonlySet<string>>;
readonly files: ReadonlyMap<string, Component>;
/** Paths observed as directories, or implied by a deeper path. */
readonly directories: ReadonlySet<string>;
}
const indexTree = (entries: readonly Entry[]): Tree => {
const children = new Map<string, Set<string>>();
const files = new Map<string, Component>();
const directories = new Set<string>();
for (const { path, kind, component } of entries) {
if (isSidecar(path)) continue;
if (kind === "file" && component !== undefined) files.set(path, component);
if (kind === "directory") directories.add(path);
const segments = path.split("/");
let parent = "";
for (const segment of segments) {
const names = children.get(parent) ?? new Set<string>();
names.add(segment);
children.set(parent, names);
parent = joinPath(parent, segment);
if (parent !== path) directories.add(parent);
}
}
return { children, files, directories };
};
const joinPath = (directory: string, name: string): string =>
directory === "" ? name : `${directory}/${name}`;
const directoryOf = (bundle: string): string => (bundle === "." ? "" : bundle);
const enclosingBundle = (
path: string,
bundles: ReadonlySet<string>,
): string | null => {
if (path === ".") return null;
const segments = path.split("/");
for (let length = segments.length - 1; length > 0; length--) {
const candidate = segments.slice(0, length).join("/");
if (bundles.has(candidate)) return candidate;
}
return bundles.has(".") ? "." : null;
};
const bundleLayout = (bundle: string, tree: Tree): Bundle["layout"] => {
const names = tree.children.get(directoryOf(bundle));
if (names?.has("Contents") === true) return "macos-deep";
if (names?.has("Versions") === true) return "versioned-framework";
return "shallow";
};
const bundleRole = (bundle: string): Bundle["role"] => {
const segments = bundle.split("/");
const name = (segments.at(-1) ?? "").toLowerCase();
const container = segments.at(-2);
if (name.endsWith(".appex")) return "app-extension";
if (name.endsWith(".xpc")) return "xpc-service";
if (name.endsWith(".framework")) return "framework";
if (name.endsWith(".systemextension")) return "system-extension";
if (name.endsWith(".dext")) return "driver-extension";
if (name.endsWith(".bundle")) {
if (container === "PlugIns") return "plug-in";
return container === "Resources" ? "resource-bundle" : "bundle";
}
if (!name.endsWith(".app")) return "plug-in";
if (container === "LoginItems" && segments.at(-3) === "Library")
return "login-item";
if (container === "Helpers") return "helper-application";
return "nested-application";
};
/** Files directly inside one directory; nested bundles are deeper paths. */
const directFiles = (directory: string, tree: Tree): string[] =>
[...(tree.children.get(directory) ?? [])]
.map((name) => joinPath(directory, name))
.filter((path) => tree.files.has(path))
.sort(compare);
/** Content directories; `Versions/Current` is a symlink outside the inventory. */
const contentDirectories = (
bundle: string,
layout: Bundle["layout"],
tree: Tree,
): string[] => {
const directory = directoryOf(bundle);
if (layout === "macos-deep") return [joinPath(directory, "Contents")];
if (layout === "shallow") return [directory];
const versions = joinPath(directory, "Versions");
// Only real version directories count: Current is a symlink, and files
// such as .DS_Store are not versions.
return [...(tree.children.get(versions) ?? [])]
.filter((version) => version !== "Current")
.map((version) => joinPath(versions, version))
.filter((version) => tree.directories.has(version))
.sort(compare);
};
const infoPlistPath = (
bundle: string,
layout: Bundle["layout"],
tree: Tree,
): string | null => {
const directories = contentDirectories(bundle, layout, tree);
// With several real versions, Versions/Current (a symlink outside the
// inventory) decides which plist applies, so the plist stays unknown.
if (directories.length !== 1) return null;
const candidates = directories
.map((directory) =>
joinPath(
directory,
layout === "versioned-framework"
? "Resources/Info.plist"
: "Info.plist",
),
)
.filter((path) => tree.files.has(path));
return candidates.length === 1 ? (candidates[0] ?? null) : null;
};
const executableCandidates = (
bundle: string,
layout: Bundle["layout"],
tree: Tree,
): string[] =>
contentDirectories(bundle, layout, tree)
.flatMap((directory) =>
directFiles(
layout === "macos-deep" ? joinPath(directory, "MacOS") : directory,
tree,
),
)
.filter((path) =>
MACH_O_FORMATS.includes(tree.files.get(path)?.format ?? ""),
);
const signingPaths = (
bundle: string,
layout: Bundle["layout"],
tree: Tree,
): string[] =>
contentDirectories(bundle, layout, tree)
.flatMap((directory) => [
joinPath(directory, "_CodeSignature/CodeResources"),
joinPath(directory, "embedded.provisionprofile"),
joinPath(directory, "embedded.mobileprovision"),
])
.filter((path) => tree.files.has(path))
.sort(compare);
/** Platforms of application roots whose layout was observed, not assumed. */
export const platformsOf = (bundles: readonly Bundle[]): ("ios" | "macos")[] =>
[
...new Set(
bundles.flatMap(({ role, layout, info_plist_path: plist }) => {
if (role !== "application") return [];
if (layout === "macos-deep") return ["macos" as const];
// An empty or partial root has no Contents/ either; require Info.plist.
if (layout === "shallow" && plist !== null) return ["ios" as const];
return [];
}),
),
].sort(compare);
const compare = (left: string, right: string): number =>
left < right ? -1 : left > right ? 1 : 0;
@@ -318,6 +318,91 @@ describe("keyed archive decoding and graph limits", () => {
});
});
describe("keyed archive object references", () => {
it("keeps referenced objects as stubs so shared and cyclic references stay finite", () => {
// Each view references its window, superview, and next key view, so
// inlining references would expand the table into an exponential tree.
const viewCount = 40;
const views = Array.from({ length: viewCount }, (_, index) => ({
$class: { UID: 1 },
NSWindow: { UID: 2 },
NSSuperview: { UID: index === 0 ? 2 : 3 + index - 1 },
NSNextKeyView: { UID: 3 + ((index + 1) % viewCount) },
NSSubviews: index + 1 < viewCount ? [{ UID: 3 + index + 1 }] : [],
NSTitle: { UID: 3 + viewCount },
}));
const parsed = parseInterfaceBuilderRecords({
$archiver: "NSKeyedArchiver",
$objects: [
"$null",
{ $classname: "NSView", $classes: ["NSView", "NSObject"] },
{ $class: { UID: 3 + viewCount + 1 }, NSContentView: { UID: 3 } },
...views,
"Title",
{ $classname: "NSWindow", $classes: ["NSWindow", "NSObject"] },
],
$top: { root: { UID: 2 } },
});
expect(parsed.objects).toHaveLength(viewCount + 1);
const view = parsed.objects.find(({ id }) => id === "3");
expect(view?.name).toBe("NSView");
expect(view?.attributes).toEqual({
NSWindow: { archiveUID: 2, className: "NSWindow" },
NSSuperview: { archiveUID: 2, className: "NSWindow" },
NSNextKeyView: { archiveUID: 4, className: "NSView" },
NSSubviews: [{ archiveUID: 4, className: "NSView" }],
NSTitle: "Title",
});
expect(parsed.hierarchy).toMatchObject([
{
objectID: "2",
children: [{ objectID: "3", children: [{ objectID: "4" }] }],
},
]);
});
it("resolves XML CF$UID references and the archived nil", () => {
const parsed = parseInterfaceBuilderRecords({
$archiver: "NSKeyedArchiver",
$objects: [
"$null",
{
$class: { CF$UID: 3 },
NSSource: { CF$UID: 2 },
source: { CF$UID: 2 },
destination: { CF$UID: 0 },
label: { CF$UID: 4 },
},
{ $class: { CF$UID: 5 } },
{
$classname: "NSNibOutletConnector",
$classes: ["NSNibOutletConnector", "NSObject"],
},
{ $class: { CF$UID: 6 }, "NS.string": "delegate" },
{ $classname: "NSButton", $classes: ["NSButton", "NSObject"] },
{
$classname: "NSMutableString",
$classes: ["NSMutableString", "NSString", "NSObject"],
},
],
$top: {},
});
expect(parsed.connections).toEqual([
expect.objectContaining({
kind: "outlet",
source_id: "2",
destination_id: null,
label: "delegate",
}),
]);
expect(parsed.objects.find(({ id }) => id === "2")).toMatchObject({
class_name: "NSButton",
});
});
});
describe("AppKit keyed archive connectors", () => {
it("reads outlet and control connectors from NS-prefixed keys", () => {
const parsed = parseInterfaceBuilderRecords({
@@ -10,7 +10,7 @@ import {
nativeInvestigationGraphSchema,
nativeInvestigationNodeSchema,
nativeInvestigationTraceLimitsSchema,
} from "./nativeInvestigationGraph.js";
} from "../nativeInvestigationGraph.js";
export { parseInterfaceBuilderRecords } from "./interfaceBuilderKeyedArchive.js";
@@ -1,6 +1,6 @@
import { z } from "zod";
import { jsonValueSchema } from "./jsonValue.js";
import { jsonValueSchema } from "../jsonValue.js";
const recordSchema = z.record(z.string(), z.unknown());
@@ -117,62 +117,130 @@ export const parseInterfaceBuilderRecords = (
};
};
/**
* A UID decodes as a one-key `UID` (binary) or `CF$UID` (XML) dictionary with
* an integer value. Any other dictionary is ordinary archive data.
*/
const archiveUid = (value: unknown): number | undefined => {
if (typeof value !== "object" || value === null || Array.isArray(value))
return undefined;
if (Object.keys(value).length !== 1) return undefined;
const item = record(value);
const marker = Object.hasOwn(item, "UID") ? item.UID : item["CF$UID"];
return typeof marker === "number" && Number.isInteger(marker)
? marker
: undefined;
};
const HIERARCHY_KEY =
/(?:subviews|contentview|childviewcontrollers|children|views)$/iu;
/**
* Read an NSKeyedArchiver object table without expanding it into a tree.
* Archived objects reference each other freely, including cycles such as a
* view and its superview, so inlining every reference grows exponentially.
* A reference instead resolves to the referenced string, or to a stub that
* names the referenced object; the hierarchy walk visits each object once.
*/
const keyedArchiveTable = (objectTable: readonly unknown[]) => {
const classNameOf = (value: unknown): string | null => {
const classReference = record(value).$class;
const uid = archiveUid(classReference);
return firstString(
record(uid === undefined ? classReference : objectTable[uid]).$classname,
);
};
/** The string an archived string object holds, if it is one. */
const archivedString = (target: unknown): string | undefined => {
if (typeof target === "string") return target;
const text = record(target)["NS.string"];
return typeof text === "string" &&
/^NS(?:Mutable)?String$/u.test(classNameOf(target) ?? "")
? text
: undefined;
};
const text = (value: unknown): string | null => {
const uid = archiveUid(value);
return firstString(
uid === undefined ? value : archivedString(objectTable[uid]),
);
};
const authoredId = (item: Record<string, unknown>): string | null =>
firstString(text(item.objectID), text(item["object-id"]));
const reference = (uid: number): unknown => {
// UID 0 is the archived nil.
const target = uid === 0 ? null : objectTable[uid];
if (target === undefined || target === null) return null;
if (typeof target !== "object") return target;
const string = archivedString(target);
if (string !== undefined) return string;
const objectId = authoredId(record(target));
return {
archiveUID: uid,
...(objectId === null ? {} : { objectID: objectId }),
className: classNameOf(target),
};
};
/** Resolve one object's own fields, leaving references to other objects as stubs. */
const resolve = (value: unknown): unknown => {
const uid = archiveUid(value);
if (uid !== undefined) return reference(uid);
if (Array.isArray(value)) return value.map(resolve);
if (typeof value !== "object" || value === null) return value;
const output: Record<string, unknown> = {};
for (const [key, child] of Object.entries(value)) {
if (key === "$class") output.className = classNameOf(value);
else output[key] = resolve(child);
}
return output;
};
const hierarchy = (start: unknown): unknown[] => {
const visited = new Set<number>();
const node = (
item: Record<string, unknown>,
uid: number | undefined,
depth: number,
): unknown[] => {
const objectId = firstString(
authoredId(item),
text(item.id),
uid === undefined ? null : String(uid),
);
const children = Object.entries(item)
.filter(([key]) => HIERARCHY_KEY.test(key))
.flatMap(([, child]) => visit(child, depth + 1));
return objectId === null ? children : [{ objectID: objectId, children }];
};
const visit = (value: unknown, depth: number): unknown[] => {
if (depth > 32) return [];
const uid = archiveUid(value);
if (uid !== undefined) {
if (visited.has(uid)) return [];
visited.add(uid);
const target = objectTable[uid];
if (Array.isArray(target)) return visit(target, depth + 1);
return typeof target === "object" && target !== null
? node(record(target), uid, depth)
: [];
}
if (Array.isArray(value))
return value.flatMap((item) => visit(item, depth + 1));
if (typeof value !== "object" || value === null) return [];
return node(record(value), undefined, depth);
};
return visit(start, 0);
};
return { resolve, hierarchy };
};
/** Project class and connection objects from an NSKeyedArchiver object table. */
const parseKeyedArchive = (
root: Record<string, unknown>,
): ReturnType<typeof parseInterfaceBuilderRecords> | null => {
if (root.$archiver !== "NSKeyedArchiver" || !Array.isArray(root.$objects))
return null;
const objectTable = root.$objects;
const resolve = (value: unknown, depth = 0): unknown => {
if (depth > 16) return null;
const uid = record(value).UID;
if (typeof uid === "number") {
const target = objectTable[uid];
const resolved = target === undefined ? null : resolve(target, depth + 1);
return typeof resolved === "object" &&
resolved !== null &&
!Array.isArray(resolved)
? { ...resolved, archiveUID: uid }
: resolved;
}
if (Array.isArray(value))
return value.map((item) => resolve(item, depth + 1));
if (typeof value !== "object" || value === null) return value;
const output: Record<string, unknown> = {};
for (const [key, child] of Object.entries(value)) {
if (key === "$class") {
const classObject = record(
typeof record(child).UID === "number"
? objectTable[record(child).UID as number]
: child,
);
output.className = firstString(classObject.$classname);
} else output[key] = resolve(child, depth + 1);
}
return output;
};
const toHierarchy = (value: unknown, depth = 0): unknown[] => {
if (depth > 32) return [];
if (Array.isArray(value))
return value.flatMap((item) => toHierarchy(item, depth + 1));
if (typeof value !== "object" || value === null) return [];
const item = record(value);
const objectId = firstString(
item.objectID,
item["object-id"],
item.id,
typeof item.archiveUID === "number" ? String(item.archiveUID) : null,
);
const children = Object.entries(item)
.filter(([key]) =>
/(?:subviews|contentview|childviewcontrollers|children|views)$/iu.test(
key,
),
)
.flatMap(([, child]) => toHierarchy(child, depth + 1));
return objectId === null ? children : [{ objectID: objectId, children }];
};
const objectTable: readonly unknown[] = root.$objects;
const { resolve, hierarchy: toHierarchy } = keyedArchiveTable(objectTable);
const objects: InterfaceBuilderObject[] = [];
const connections: InterfaceBuilderConnection[] = [];
let objectCount = 0;
@@ -252,8 +320,7 @@ const parseKeyedArchive = (
}
}
const top = record(root.$top);
const topObject = resolve(top.root ?? top.UITopLevelObjectsKey);
const hierarchy = toHierarchy(topObject);
const hierarchy = toHierarchy(top.root ?? top.UITopLevelObjectsKey);
const classes = Object.fromEntries(
objectTable.flatMap((raw) => {
const item = record(raw);
@@ -327,7 +394,11 @@ const classifyObject = (
const value = className?.toLowerCase() ?? "";
if (value.includes("constraint")) return "constraint";
if (value.includes("layoutguide")) return "layout_guide";
if (value.includes("placeholder") || value.includes("firstresponder"))
if (
value.includes("placeholder") ||
value.includes("firstresponder") ||
value === "uiproxyobject"
)
return "placeholder";
if (
value.includes("image") ||
@@ -1,5 +1,5 @@
import { z } from "zod";
import { jsonValueSchema, type JsonValue } from "./jsonValue.js";
import { jsonValueSchema, type JsonValue } from "../jsonValue.js";
/** Select one archive within the active bundle and optionally one named root. */
export const keyedArchiveInputSchema = z.strictObject({
@@ -1,6 +1,6 @@
import { z } from "zod";
import type { JsonValue } from "./jsonValue.js";
import type { JsonValue } from "../jsonValue.js";
const MAX_PLIST_DEPTH = 128;
-267
View File
@@ -1,267 +0,0 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import { parseArtifactInventoryEvidence } from "./artifactInventoryEvidence.js";
import { evidenceSchema } from "./evidence.js";
import { digestSchema } from "./../domain/digests.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const pathSchema = z.string().min(1);
const componentSchema = z.strictObject({
path: pathSchema,
artifact_id: prefixedDigestSchema("art"),
sha256: digestSchema,
format: z.string().min(1),
});
/** Authenticated artifact inventory pages projected as one Apple application. */
export const appleApplicationProjectionInputSchema = z.strictObject({
inventory_evidence: z.array(evidenceSchema).min(1),
});
/** Deterministic, execution-free Apple application inventory projection. */
export const appleApplicationProjectionResultSchema = z.strictObject({
projection_id: prefixedDigestSchema("aap"),
root_sha256: digestSchema,
root_format: z.literal("ipa"),
source_evidence_ids: z.array(evidenceIdSchema).min(1),
application_roots: z.array(pathSchema),
components: z.strictObject({
bundle_metadata: z.array(componentSchema),
executables: z.array(componentSchema),
frameworks: z.array(componentSchema),
native_libraries: z.array(componentSchema),
javascript: z.array(componentSchema),
signing: z.array(componentSchema),
}),
runtime_families: z.array(
z.enum([
"native",
"swift-objective-c",
"javascript",
"react-native",
"flutter",
"unity",
]),
),
bridge_candidates: z.array(
z.strictObject({
source_path: pathSchema,
native_path: pathSchema,
basis: z.enum([
"javascript-and-native-content",
"react-native-convention",
"flutter-convention",
"unity-convention",
]),
}),
),
coverage: z.strictObject({
status: z.enum(["complete-within-inventory", "partial"]),
inventory_complete: z.boolean(),
}),
limitations: z.array(z.string().min(1)),
});
export type AppleApplicationProjectionInput = z.infer<
typeof appleApplicationProjectionInputSchema
>;
export type AppleApplicationProjectionResult = z.infer<
typeof appleApplicationProjectionResultSchema
>;
type Component = z.infer<typeof componentSchema>;
/** Project exact IPA paths and hashes without parsing or executing target code. */
export const projectAppleApplication = (
input: AppleApplicationProjectionInput,
): AppleApplicationProjectionResult => {
const parsed = appleApplicationProjectionInputSchema.parse(input);
const { evidence, inventory } = parseArtifactInventoryEvidence(
parsed.inventory_evidence,
);
if (inventory.manifest.root_format !== "ipa")
throw new TypeError("Apple application projection requires IPA Evidence");
const nodes = new Map(
inventory.nodes.map((node) => [node.artifact_id, node]),
);
const all = inventory.occurrences
.filter(
(occurrence) =>
occurrence.artifact_id !== null && occurrence.logical_path !== ".",
)
.map((occurrence) => {
const node = nodes.get(occurrence.artifact_id ?? "");
if (node === undefined)
throw new TypeError(
"Apple application occurrence has no artifact node",
);
return {
path: occurrence.logical_path,
artifact_id: node.artifact_id,
sha256: node.sha256,
format: node.format,
} satisfies Component;
});
const roots = [
...new Set(
inventory.occurrences.flatMap(({ logical_path: path }) => {
const match = /^(Payload\/[^/]+\.app)(?:\/|$)/u.exec(path);
return match?.[1] === undefined ? [] : [match[1]];
}),
),
].sort(compare);
const classified = classifyComponents(all, roots);
const runtimeFamilies = identifyRuntimeFamilies(all);
const bridgeProjection = identifyBridgeCandidates(
classified.javascript,
deduplicateComponents([
...classified.executables,
...classified.native_libraries,
]),
);
const limitations = projectionLimitations(inventory.complete, roots);
const withoutId = {
root_sha256: inventory.manifest.root_sha256,
root_format: "ipa" as const,
source_evidence_ids: evidence
.map(({ evidence_id: id }) => id)
.sort(compare),
application_roots: roots,
components: classified,
runtime_families: runtimeFamilies,
bridge_candidates: bridgeProjection.candidates,
coverage: {
status: inventory.complete
? ("complete-within-inventory" as const)
: ("partial" as const),
inventory_complete: inventory.complete,
},
limitations,
};
return appleApplicationProjectionResultSchema.parse({
...withoutId,
projection_id: `aap_${digest(withoutId)}`,
});
};
const classifyComponents = (
all: readonly Component[],
roots: readonly string[],
) => {
const withinApp = (path: string): boolean =>
roots.some((root) => path.startsWith(`${root}/`));
return {
bundle_metadata: all.filter(({ path }) =>
/(?:^|\/)Info\.plist$/u.test(path),
),
executables: all.filter(
({ path, format }) =>
withinApp(path) && ["mach-o", "mach-o-universal"].includes(format),
),
frameworks: all.filter(({ path }) => /\.framework\//u.test(path)),
native_libraries: all.filter(({ path }) => /\.(?:dylib|so)$/iu.test(path)),
javascript: all.filter(({ format }) => format === "javascript-bundle"),
signing: all.filter(({ path }) =>
/(?:^|\/)(?:embedded\.mobileprovision|_CodeSignature\/CodeResources)$/u.test(
path,
),
),
};
};
const deduplicateComponents = (values: readonly Component[]): Component[] =>
[...new Map(values.map((value) => [value.path, value])).values()].sort(
(left, right) => compare(left.path, right.path),
);
const identifyRuntimeFamilies = (all: readonly Component[]) => {
const paths = all.map(({ path }) => path.toLowerCase());
const families = new Set<
z.infer<
typeof appleApplicationProjectionResultSchema
>["runtime_families"][number]
>();
if (all.some(({ format }) => ["mach-o", "mach-o-universal"].includes(format)))
families.add("native");
if (paths.some((path) => /\.(?:dylib|framework\/[^/]+)$/u.test(path)))
families.add("swift-objective-c");
if (all.some(({ format }) => format === "javascript-bundle"))
families.add("javascript");
if (
paths.some(
(path) =>
path.includes("reactnative") ||
path.includes("react.framework") ||
path.includes("hermes"),
)
)
families.add("react-native");
if (
paths.some(
(path) =>
path.includes("flutter.framework") || path.includes("app.framework"),
)
)
families.add("flutter");
if (paths.some((path) => path.includes("unityframework.framework")))
families.add("unity");
return [...families].sort(compare);
};
const identifyBridgeCandidates = (
scripts: readonly Component[],
native: readonly Component[],
) => ({
candidates: scripts.flatMap((script) =>
native.map((item) => ({
source_path: script.path,
native_path: item.path,
basis: bridgeBasis(item.path),
})),
),
});
const bridgeBasis = (
path: string,
):
| "javascript-and-native-content"
| "react-native-convention"
| "flutter-convention"
| "unity-convention" => {
const lower = path.toLowerCase();
if (lower.includes("react")) return "react-native-convention";
if (lower.includes("flutter") || lower.includes("app.framework"))
return "flutter-convention";
if (lower.includes("unity")) return "unity-convention";
return "javascript-and-native-content";
};
const projectionLimitations = (
complete: boolean,
roots: readonly string[],
): string[] => [
...(!complete
? ["Source inventory pages are incomplete; absence is unknown."]
: []),
...(roots.length === 0
? [
"No Payload/*.app directory was present in the supplied inventory pages.",
]
: []),
"Bundle identifiers and signing claims require dedicated plist and CMS parsing; this projection reports only exact paths and hashes.",
"Bridge candidates are path-based hypotheses, not observed runtime calls.",
];
const compare = (left: string, right: string): number =>
left < right ? -1 : left > right ? 1 : 0;
const digest = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError("Apple application projection is not canonical JSON");
return createHash("sha256").update(encoded).digest("hex");
};
+2
View File
@@ -4,6 +4,8 @@ export type BinaryArchitecture = "x86" | "x86_64" | "arm" | "arm64";
interface BinaryTargetIdentity {
readonly path: string;
readonly sourcePath?: string;
/** Info.plist of the app bundle the target was resolved from. */
readonly bundleInfoPlist?: string;
readonly sha256: string;
}
@@ -157,13 +157,12 @@ const nativeRequire = (
):
| { readonly specifier: string; readonly member: string | null }
| undefined => {
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
const nested = t.isNode(node.object)
? nativeRequire(node.object)
: undefined;
if (nested === undefined) return undefined;
const member = semanticStaticPropertyName(node.property, node.computed);
return { ...nested, member: member === "" ? nested.member : member };
let member: string | null = null;
while (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
if (!t.isNode(node.object)) return undefined;
const property = semanticStaticPropertyName(node.property, node.computed);
if (member === null && property !== "") member = property;
node = node.object;
}
if (!t.isCallExpression(node)) return undefined;
const name = calleeName(node.callee);
@@ -175,7 +174,7 @@ const nativeRequire = (
return undefined;
const specifier = stringValue(argumentNode(node.arguments[0]));
return specifier !== undefined && isNativeSpecifier(specifier, "require")
? { specifier, member: null }
? { specifier, member }
: undefined;
};
@@ -119,14 +119,30 @@ const addExport = (output: Set<string>, name: string): void => {
};
const memberPath = (node: t.Node | null | undefined): string => {
if (node === undefined || node === null) return "";
if (t.isIdentifier(node) || t.isPrivateName(node))
return t.isIdentifier(node) ? node.name : "";
if (t.isThisExpression(node)) return "this";
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
const object = t.isNode(node.object) ? memberPath(node.object) : "";
const property = propertyName(node.property);
return object === "" ? property : `${object}.${property}`;
const properties: string[] = [];
let current = node;
while (
current !== undefined &&
current !== null &&
(t.isMemberExpression(current) || t.isOptionalMemberExpression(current))
) {
properties.push(propertyName(current.property));
current = t.isNode(current.object) ? current.object : undefined;
}
return "";
const root =
current !== undefined && t.isIdentifier(current)
? current.name
: current !== undefined && t.isThisExpression(current)
? "this"
: "";
if (properties.length === 0) return root;
properties.reverse();
const path = root === "" ? [] : [root];
for (const property of properties) {
if (path.length === 0 && property === "") continue;
path.push(property);
}
return path.join(".");
};
@@ -192,6 +192,51 @@ describe("JavaScript semantic analysis: calls 2", () => {
).not.toBe(left.functionFingerprints[0]?.components.literalSetSha256);
});
it("keeps fingerprint relations ordered and effects scoped to their owner", () => {
const ordered = analyzeJavaScriptSemantics(`
function first() {}
function second(one, two) {}
function ordered() { first(); second(1, 2); }
function timerOwner() { setTimeout(work, 10); }
function networkOwner() { fetch('/data'); }
function noEffects() { return 1; }
`);
const reversed = analyzeJavaScriptSemantics(`
function first() {}
function second(one, two) {}
function ordered() { second(1, 2); first(); }
function timerOwner() { setTimeout(work, 10); }
function networkOwner() { fetch('/data'); }
function noEffects() { return 1; }
`);
const fingerprint = (ir: typeof ordered, name: string) =>
ir.functionFingerprints.find((value) =>
ir.callables.some(
(callable) =>
callable.callableId === value.callableId && callable.name === name,
),
);
expect(
fingerprint(ordered, "ordered")?.components.relationShapeSha256,
).not.toBe(
fingerprint(reversed, "ordered")?.components.relationShapeSha256,
);
expect(fingerprint(ordered, "timerOwner")?.components.effects).toContain(
"timer",
);
expect(fingerprint(ordered, "networkOwner")?.components.effects).toContain(
"network",
);
expect(fingerprint(ordered, "noEffects")?.components.effects).toEqual([]);
expect(
fingerprint(ordered, "timerOwner")?.components.effects,
).not.toContain("network");
expect(
fingerprint(ordered, "networkOwner")?.components.effects,
).not.toContain("timer");
});
it("retains ambiguous local callees and explicit dynamic frontiers", () => {
const ir = analyzeJavaScriptSemantics(`
function left(value) { return value; }
@@ -149,6 +149,31 @@ describe("JavaScript semantic analysis: dataflow 1", () => {
});
});
describe("JavaScript semantic call result flows", () => {
it("links only directly assigned scalar call results", () => {
const ir = analyzeJavaScriptSemantics(`
function run() {
const direct = produce();
const { field } = unpack();
const nested = outer(inner());
return direct;
}
`);
const bindingNames = new Map(
ir.bindings.map(({ bindingId, name }) => [bindingId, name]),
);
expect(
ir.callResultFlows.map(({ bindingId }) => bindingNames.get(bindingId)),
).toEqual(["direct", "nested"]);
expect(ir.callSites).toHaveLength(4);
expect(ir.callResultFlows.map(({ callSiteId }) => callSiteId)).toEqual([
ir.callSites[0]?.callSiteId,
ir.callSites[2]?.callSiteId,
]);
});
});
describe("JavaScript semantic analysis: read-modify-write", () => {
it.each(["+= 1", "++", "--", "||= 1", "&&= 1", "??= 1"])(
"retains the property read in a read-modify-write operation: %s",
@@ -0,0 +1,154 @@
import * as t from "@babel/types";
import { expect, it } from "vitest";
import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
import { onlyBinding, origin } from "./javascriptSemanticAnalysis.fixture.js";
import { parseJavaScriptSource } from "./javascriptSourceParser.js";
import { calleeName } from "./javascriptStaticAnalysisHelpers.js";
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
const memberChain = ".next".repeat(12_000);
it("retains native addon observations through a deep member initializer", () => {
const analysis = analyzeJavaScriptStaticSource(
`const value = require("./addon.node")${memberChain}.last[""];`,
);
expect(analysis.electron.native_addon_bindings).toEqual([
expect.objectContaining({ specifier: "./addon.node", members: ["last"] }),
]);
expect(analysis.parse_error_count).toBe(0);
});
it("keeps a deep non-native initializer outside native addon observations", () => {
const analysis = analyzeJavaScriptStaticSource(
`const value = root${memberChain}.last;`,
);
expect(analysis.electron.native_addon_bindings).toEqual([]);
expect(analysis.parse_status).toBe("complete");
});
it("retains unknown value diagnostics and references after a deep member initializer", () => {
const ir = analyzeJavaScriptSemantics(
`const value = root${memberChain}.last;`,
);
expect(ir.coverage).toEqual({ status: "complete", omittedCount: 0 });
expect(onlyBinding(ir, "value")).toMatchObject({
value: { status: "unknown", reason: "Cannot project last from unknown." },
provenance: { status: "unknown", reason: "Unbound identifier root." },
});
expect(ir.references.map(({ name, role }) => ({ name, role }))).toEqual([
{ name: "root", role: "read" },
]);
});
it.each([
`const value = require("./dependency.js")${memberChain}[""].last;`,
`const dependency = require("./dependency.js"); const value = dependency${memberChain}[""].last;`,
`const value = require("./dependency.js")?.next${memberChain}[""].last;`,
])("preserves the full literal module path (case %#)", (source) => {
const ir = analyzeJavaScriptSemantics(source);
const path = origin(onlyBinding(ir, "value"));
expect(path.specifier).toBe("./dependency.js");
expect(path.importedPath).toEqual([
...(source.includes("?.next") ? ["next"] : []),
...Array.from({ length: 12_000 }, () => "next"),
"",
"last",
]);
expect(ir.coverage.status).toBe("complete");
});
it("retains a deep CommonJS re-export path without inventing dynamic module links", () => {
const ir = analyzeJavaScriptSemantics(`
module.exports.result = require("./dependency.js")${memberChain}.last;
const dynamic = require("./other.js")${memberChain}[key].last;
`);
expect(ir.moduleLinks).toEqual([
expect.objectContaining({
kind: "commonjs-export",
specifier: "./dependency.js",
importedName: "last",
exportedName: "result",
}),
]);
expect(onlyBinding(ir, "dynamic").provenance).toMatchObject({
status: "unknown",
reason: "Dynamic provenance member.",
});
});
it("invalidates a deep mutation while retaining unrelated literal properties", () => {
const ir = analyzeJavaScriptSemantics(`
const root = { untouched: "retained" };
root${memberChain}.last = 1;
const value = root.untouched;
`);
expect(onlyBinding(ir, "root").value).toEqual({
status: "object",
properties: [
{ name: "untouched", value: { status: "literal", value: "retained" } },
],
unknownProperties: true,
omittedProperties: null,
});
expect(onlyBinding(ir, "value").value).toEqual({
status: "literal",
value: "retained",
});
});
it("retains the complete location and unresolved target of a deep call", () => {
const callee = `root${memberChain}.last`;
const ir = analyzeJavaScriptSemantics(`${callee}();`);
expect(ir.callSites).toEqual([
expect.objectContaining({
kind: "call",
resolution: "unresolved",
calleeCallableIds: [],
calleeLocation: {
start: { line: 1, column: 0 },
end: { line: 1, column: callee.length },
},
}),
]);
});
it("retains deep default values without confusing their reads with parameter bindings", () => {
const ir = analyzeJavaScriptSemantics(
`export function inspect(value = root${memberChain}.last) { return value; }`,
);
expect(ir.references.map(({ name, role }) => ({ name, role }))).toEqual([
{ name: "root", role: "read" },
{ name: "value", role: "read" },
]);
expect(ir.coverage.status).toBe("complete");
});
it("keeps a shadowed require local through a deep member initializer", () => {
const ir = analyzeJavaScriptSemantics(
`function inspect(require) { const value = require("./dependency.js")${memberChain}.last; return value; }`,
);
expect(ir.moduleLinks).toEqual([]);
expect(onlyBinding(ir, "value").provenance.origins).toEqual([]);
});
it.each([
["root.first.last()", "root.first.last"],
['root[""].last()', "root..last"],
['("")[""].last()', "last"],
['("")[""]()', ""],
["root[0].last()", "root.0.last"],
["root[key].last()", "root.[computed@5].last"],
["root?.first.last()", "root.first.last"],
[`root${memberChain}.last()`, `root${memberChain}.last`],
])("preserves exact callee syntax (case %#)", (source, expected) => {
const file = parseJavaScriptSource(source);
const statement = file?.program.body[0];
if (
!t.isExpressionStatement(statement) ||
(!t.isCallExpression(statement.expression) &&
!t.isOptionalCallExpression(statement.expression))
)
throw new Error("Expected parsed call expression");
expect(calleeName(statement.expression.callee)).toBe(expected);
});
@@ -0,0 +1,40 @@
import { describe, expect, it } from "vitest";
import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
describe("JavaScript semantic analysis: recovered arguments", () => {
it.each([
{ source: "0(,)", indexes: [] },
{ source: 'call(, "kept", , 42)', indexes: [1, 3] },
{ source: 'call?.(, "kept")', indexes: [1] },
{ source: 'new Thing(, "kept")', indexes: [1] },
])(
"retains argument positions in recovered syntax: $source",
({ source, indexes }) => {
const ir = analyzeJavaScriptSemantics(source);
expect(ir.coverage.status).toBe("partial");
expect(ir.callSites).toHaveLength(1);
expect(ir.callSites[0]?.arguments.map(({ index }) => index)).toEqual(
indexes,
);
expect(ir.limitations.join(" ")).toMatch(/parser recovered/iu);
},
);
it("keeps recovered argument flows bound to their original parameter", () => {
const ir = analyzeJavaScriptSemantics(
"function select(first, second) { return second; } const value = 42; select(, value);",
);
const second = ir.bindings.find(({ name }) => name === "second");
expect(ir.coverage.status).toBe("partial");
expect(second).toBeDefined();
expect(ir.argumentFlows).toEqual([
expect.objectContaining({
argumentIndex: 1,
parameterBindingId: second?.bindingId,
}),
]);
});
});
@@ -183,9 +183,7 @@ const collectCallResultFlow = (
context.ancestors,
context.state,
).filter(({ projectionPath }) => projectionPath.length === 0)) {
const binding = [...context.state.bindingsById.values()].find(
({ bindingId }) => bindingId === assigned.bindingId,
);
const binding = context.state.bindingsById.get(assigned.bindingId);
if (binding === undefined) continue;
const identifierRange = range(assigned.identifier);
const definition = binding.definitions.find(
@@ -210,10 +208,13 @@ const retainedArguments = (
| t.SpreadElement
| t.JSXNamespacedName
| t.ArgumentPlaceholder
| null
)[],
): JavaScriptSemanticCallSite["arguments"] => {
const retained: JavaScriptSemanticCallSite["arguments"][number][] = [];
for (const [index, node] of nodes.entries()) {
// Babel recovery can leave null slots; retain the other argument positions.
if (node === null) continue;
retained.push({
index,
location: range(node),
@@ -50,30 +50,36 @@ export const collectJavaScriptSemanticFingerprints = (
resourceOperations,
parserPartial,
} = input;
const callSitesByCaller = groupByOwner(
calls.callSites,
({ callerCallableId }) => callerCallableId,
);
const captureCountByCallable = countByOwner(
calls.closureCaptures,
({ callableId }) => callableId,
);
const promiseEffectsByOwner = groupByOwner(promises, ownerId);
const eventEffectsByOwner = groupByOwner(events, ownerId);
const timerEffectsByOwner = groupByOwner(timers, ownerId);
const childProcessEffectsByOwner = groupByOwner(
[...childProcessSpawns, ...childProcessInteractions],
ownerId,
);
const networkEffectsByOwner = groupByOwner(requestOperations, ownerId);
const resourceEffectsByOwner = groupByOwner(resourceOperations, ownerId);
return callables.flatMap((callable) => {
if (callable.kind === "class") return [];
const node = state.callableNodesById.get(callable.callableId);
if (node === undefined) return [];
const syntax = fingerprintSyntax(node, callable.callableId);
const promiseEffects = promises.filter(
({ ownerCallableId }) => ownerCallableId === callable.callableId,
);
const eventEffects = events.filter(
({ ownerCallableId }) => ownerCallableId === callable.callableId,
);
const timerEffects = timers.filter(
({ ownerCallableId }) => ownerCallableId === callable.callableId,
);
const childProcessEffects = [
...childProcessSpawns,
...childProcessInteractions,
].filter(({ ownerCallableId }) => ownerCallableId === callable.callableId);
const networkEffects = requestOperations.filter(
({ ownerCallableId }) => ownerCallableId === callable.callableId,
);
const resourceEffects = resourceOperations.filter(
({ ownerCallableId }) => ownerCallableId === callable.callableId,
);
const promiseEffects = promiseEffectsByOwner.get(callable.callableId) ?? [];
const eventEffects = eventEffectsByOwner.get(callable.callableId) ?? [];
const timerEffects = timerEffectsByOwner.get(callable.callableId) ?? [];
const childProcessEffects =
childProcessEffectsByOwner.get(callable.callableId) ?? [];
const networkEffects = networkEffectsByOwner.get(callable.callableId) ?? [];
const resourceEffects =
resourceEffectsByOwner.get(callable.callableId) ?? [];
return [
{
callableId: callable.callableId,
@@ -86,7 +92,12 @@ export const collectJavaScriptSemanticFingerprints = (
normalizedAstSha256: digest(syntax.normalizedTokens),
controlFlowSha256: digest(syntax.controlFlowTokens),
relationShapeSha256: digest(
relationShape(callable, calls, promiseEffects),
relationShape(
callable,
callSitesByCaller.get(callable.callableId) ?? [],
captureCountByCallable.get(callable.callableId) ?? 0,
promiseEffects,
),
),
literalSetSha256: digest(
[...new Set(syntax.literals)].sort(compareCodePoints),
@@ -114,6 +125,36 @@ export const collectJavaScriptSemanticFingerprints = (
});
};
const ownerId = <T extends { readonly ownerCallableId: string | null }>(
value: T,
): string | null => value.ownerCallableId;
const groupByOwner = <T, K extends string | null>(
values: readonly T[],
getOwner: (value: T) => K,
): Map<K, T[]> => {
const grouped = new Map<K, T[]>();
for (const value of values) {
const owner = getOwner(value);
const ownedValues = grouped.get(owner);
if (ownedValues === undefined) grouped.set(owner, [value]);
else ownedValues.push(value);
}
return grouped;
};
const countByOwner = <T, K extends string | null>(
values: readonly T[],
getOwner: (value: T) => K,
): Map<K, number> => {
const counts = new Map<K, number>();
for (const value of values) {
const owner = getOwner(value);
counts.set(owner, (counts.get(owner) ?? 0) + 1);
}
return counts;
};
interface FingerprintSyntax {
readonly normalizedTokens: readonly string[];
readonly controlFlowTokens: readonly string[];
@@ -229,21 +270,16 @@ const semanticLiteral = (node: t.Node): string | null => {
const relationShape = (
callable: JavaScriptSemanticCallable,
calls: JavaScriptSemanticCallAnalysis,
callSites: JavaScriptSemanticCallAnalysis["callSites"],
captureCount: number,
promises: readonly JavaScriptSemanticPromiseOperation[],
): string[] => [
`returns:${String(callable.returnSites.length)}:${callable.returnCoverage.status}`,
...calls.callSites
.filter(({ callerCallableId }) => callerCallableId === callable.callableId)
.map(
({ kind, resolution, arguments: args, calleeCallableIds }) =>
`call:${kind}:${resolution}:${String(args.length)}:${String(calleeCallableIds.length)}`,
),
`captures:${String(
calls.closureCaptures.filter(
({ callableId }) => callableId === callable.callableId,
).length,
)}`,
...callSites.map(
({ kind, resolution, arguments: args, calleeCallableIds }) =>
`call:${kind}:${resolution}:${String(args.length)}:${String(calleeCallableIds.length)}`,
),
`captures:${String(captureCount)}`,
...promises.map(
({ kind, method, ownership, sourceResolution }) =>
`promise:${kind}:${method}:${ownership}:${sourceResolution}`,
@@ -39,11 +39,18 @@ export const collectSemanticMemberMutations = (
return;
}
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
markValue(
node.object,
[semanticStaticPropertyKey(node.property, node.computed), ...path],
bindings,
);
const members: (string | null)[] = [];
let current: t.Node = node;
while (
t.isMemberExpression(current) ||
t.isOptionalMemberExpression(current)
) {
members.push(
semanticStaticPropertyKey(current.property, current.computed),
);
current = current.object;
}
markValue(current, [...members.reverse(), ...path], bindings);
return;
}
for (const value of referencedValues(node, path))
@@ -1,7 +1,6 @@
import * as t from "@babel/types";
import type {
JavaScriptModuleOrigin,
JavaScriptSemanticBinding,
JavaScriptSemanticModuleLink,
JavaScriptSemanticReference,
@@ -14,6 +13,7 @@ import {
type JavaScriptSemanticAnalysisState,
type JavaScriptSemanticScopeState,
} from "./javascriptSemanticState.js";
import { semanticRequireOrigin } from "./javascriptSemanticRequireOrigin.js";
import { compareCodePoints } from "../canonicalOrdering.js";
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
import {
@@ -100,12 +100,16 @@ export const collectSemanticReferences = (
): JavaScriptSemanticReference[] => {
const output: JavaScriptSemanticReference[] = [];
const seen = new Set<string>();
const patterns: t.Node[] = [];
traverseJavaScriptAst(program, {
enter: (node, parent, readAncestors) => {
if (isPatternNode(node)) patterns.push(node);
if (
!t.isIdentifier(node) ||
parent === null ||
(name !== undefined && node.name !== name)
(name !== undefined && node.name !== name) ||
(isNonReferenceKey(node, parent) &&
!patterns.some((pattern) => bindsIdentifier(pattern, parent, node)))
)
return;
const role = semanticIdentifierRole(node, parent, readAncestors());
@@ -138,6 +142,9 @@ export const collectSemanticReferences = (
});
}
},
exit: (node) => {
if (isPatternNode(node)) patterns.pop();
},
});
return output;
};
@@ -174,40 +181,6 @@ export const immutableSemanticBindings = (
}))
.sort((left, right) => compareCodePoints(left.bindingId, right.bindingId));
/** Recover a literal require origin plus an optional member chain. */
const semanticModuleOrigin = (
node: t.Node | null | undefined,
projection: readonly (string | number | null)[],
state: JavaScriptSemanticAnalysisState,
): JavaScriptModuleOrigin | undefined => {
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
const nested = t.isNode(node.object)
? semanticModuleOrigin(node.object, projection, state)
: undefined;
const member = semanticStaticPropertyKey(node.property, node.computed);
return nested === undefined || member === null
? undefined
: { ...nested, importedPath: [...nested.importedPath, member] };
}
if (
!t.isCallExpression(node) ||
!t.isIdentifier(node.callee, { name: "require" })
)
return undefined;
if (
resolveSemanticBindingState(state, node.callee, "require") !== undefined ||
semanticResolutionBlocked(state, node.callee, "require")
)
return undefined;
const specifier = stringValue(node.arguments[0]);
return specifier === undefined || projection.includes(null)
? undefined
: {
specifier,
importedPath: projection.map((segment) => String(segment)),
};
};
export {
semanticStaticPropertyKey,
semanticStaticPropertyName,
@@ -318,7 +291,7 @@ const collectRequireLink = (
node: t.VariableDeclarator,
state: JavaScriptSemanticAnalysisState,
): void => {
const origin = semanticModuleOrigin(node.init, [], state);
const origin = semanticRequireOrigin(node.init, state);
if (origin === undefined) return;
for (const binding of requirePatternBindings(node.id, origin.importedPath))
addModuleLink(state, {
@@ -364,7 +337,7 @@ const collectCommonJsExport = (
): void => {
const exportedName = commonJsExportName(node.left, state);
if (exportedName === undefined) return;
const origin = semanticModuleOrigin(node.right, [], state);
const origin = semanticRequireOrigin(node.right, state);
addModuleLink(state, {
kind: "commonjs-export",
specifier: origin?.specifier ?? null,
@@ -0,0 +1,38 @@
import * as t from "@babel/types";
import type { JavaScriptModuleOrigin } from "./javascriptSemanticIr.js";
import {
resolveSemanticBindingState,
semanticResolutionBlocked,
type JavaScriptSemanticAnalysisState,
} from "./javascriptSemanticState.js";
import { semanticStaticPropertyKey } from "./javascriptAstValues.js";
import { stringValue } from "./javascriptStaticAnalysisHelpers.js";
/** Recover an unshadowed literal require origin and its exact member path. */
export const semanticRequireOrigin = (
node: t.Node | null | undefined,
state: JavaScriptSemanticAnalysisState,
): JavaScriptModuleOrigin | undefined => {
const members: string[] = [];
while (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
const member = semanticStaticPropertyKey(node.property, node.computed);
if (member === null || !t.isNode(node.object)) return undefined;
members.push(member);
node = node.object;
}
if (
!t.isCallExpression(node) ||
!t.isIdentifier(node.callee, { name: "require" })
)
return undefined;
if (
resolveSemanticBindingState(state, node.callee, "require") !== undefined ||
semanticResolutionBlocked(state, node.callee, "require")
)
return undefined;
const specifier = stringValue(node.arguments[0]);
return specifier === undefined
? undefined
: { specifier, importedPath: members.reverse() };
};
@@ -51,3 +51,16 @@ it("preserves source-tree enter/exit order and detached ancestor snapshots", ()
],
]);
});
it("skips sparse child slots without disturbing sibling visit order", () => {
const parsed = parseJavaScriptSource("const values = [first, , second];");
if (parsed === null)
throw new TypeError("Expected a parsed JavaScript fixture");
const identifiers: string[] = [];
traverseJavaScriptAst(parsed.program, {
enter: (node) => {
if (t.isIdentifier(node)) identifiers.push(node.name);
},
});
expect(identifiers).toEqual(["values", "first", "second"]);
});
@@ -51,11 +51,19 @@ interface TraversalFrame {
}
const childNodes = (node: t.Node): t.Node[] => {
const keys: readonly string[] = t.VISITOR_KEYS[node.type] ?? [];
return keys.flatMap((key) => {
const keys = t.VISITOR_KEYS[node.type];
if (keys === undefined) return [];
const children: t.Node[] = [];
for (const key of keys) {
const value: unknown = Reflect.get(node, key);
if (t.isNode(value)) return [value];
if (!Array.isArray(value)) return [];
return value.filter((item): item is t.Node => t.isNode(item));
});
if (t.isNode(value)) {
children.push(value);
continue;
}
if (!Array.isArray(value)) continue;
for (const item of value) {
if (t.isNode(item)) children.push(item);
}
}
return children;
};
@@ -4,17 +4,15 @@ import { invalidateSemanticMutationPath } from "./javascriptSemanticMutationValu
import type {
JavaScriptBindingProvenance,
JavaScriptModuleOrigin,
JavaScriptSemanticProperty,
JavaScriptSemanticValue,
} from "./javascriptSemanticIr.js";
import {
resolveSemanticBindingState,
semanticResolutionBlocked,
type JavaScriptSemanticAnalysisState,
type JavaScriptSemanticBindingState,
} from "./javascriptSemanticState.js";
import { stringValue } from "./javascriptStaticAnalysisHelpers.js";
import { semanticRequireOrigin } from "./javascriptSemanticRequireOrigin.js";
import { compareCodePoints } from "../canonicalOrdering.js";
import { semanticStaticPropertyKey } from "./javascriptAstValues.js";
import {
@@ -253,15 +251,28 @@ const evaluateMember = (
node: t.MemberExpression | t.OptionalMemberExpression,
context: EvaluationContext,
): JavaScriptSemanticValue => {
if (!t.isNode(node.object))
return { status: "unknown", reason: "Unsupported member base." };
const key =
semanticStaticPropertyKey(node.property, node.computed) ?? undefined;
if (key === undefined)
return { status: "unknown", reason: "Dynamic member key." };
return projectValue(evaluateExpression(node.object, nestedContext(context)), [
key,
]);
const keys: string[] = [];
let current: t.Node = node;
let value: JavaScriptSemanticValue | undefined;
while (
t.isMemberExpression(current) ||
t.isOptionalMemberExpression(current)
) {
if (!t.isNode(current.object)) {
value = { status: "unknown", reason: "Unsupported member base." };
break;
}
const key = semanticStaticPropertyKey(current.property, current.computed);
if (key === null) {
value = { status: "unknown", reason: "Dynamic member key." };
break;
}
keys.push(key);
current = current.object;
}
value ??= evaluateExpression(current, nestedContext(context));
for (const key of keys.reverse()) value = projectValue(value, [key]);
return value;
};
const evaluateAddition = (
@@ -425,7 +436,7 @@ const provenanceForExpression = (
node: t.Node,
context: EvaluationContext,
): JavaScriptBindingProvenance => {
const required = requireOrigin(node, context.state);
const required = semanticRequireOrigin(node, context.state);
if (required !== undefined) return semanticOriginsProvenance([required]);
if (t.isIdentifier(node)) {
const binding = resolveSemanticBindingState(context.state, node, node.name);
@@ -437,25 +448,37 @@ const provenanceForExpression = (
: provenanceForBinding(binding, nestedContext(context));
}
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
if (!t.isNode(node.object))
return semanticUnresolvedProvenance(
"unknown",
"Unsupported member base.",
const members: string[] = [];
let current: t.Node = node;
while (
t.isMemberExpression(current) ||
t.isOptionalMemberExpression(current)
) {
if (!t.isNode(current.object))
return semanticUnresolvedProvenance(
"unknown",
"Unsupported member base.",
);
const member = semanticStaticPropertyKey(
current.property,
current.computed,
);
const member =
semanticStaticPropertyKey(node.property, node.computed) ?? undefined;
if (typeof member !== "string")
return semanticUnresolvedProvenance(
"unknown",
"Dynamic provenance member.",
);
const base = provenanceForExpression(node.object, nestedContext(context));
if (member === null)
return semanticUnresolvedProvenance(
"unknown",
"Dynamic provenance member.",
);
members.push(member);
current = current.object;
}
const base = provenanceForExpression(current, nestedContext(context));
const path = members.reverse();
return base.status !== "module"
? base
: semanticOriginsProvenance(
base.origins.map((origin) => ({
...origin,
importedPath: [...origin.importedPath, member],
importedPath: [...origin.importedPath, ...path],
})),
);
}
@@ -480,33 +503,6 @@ const provenanceForExpression = (
return semanticLocalProvenance();
};
const requireOrigin = (
node: t.Node,
state: JavaScriptSemanticAnalysisState,
): JavaScriptModuleOrigin | undefined => {
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
if (!t.isNode(node.object)) return undefined;
const nested = requireOrigin(node.object, state);
const member =
semanticStaticPropertyKey(node.property, node.computed) ?? undefined;
return nested === undefined || typeof member !== "string"
? undefined
: { ...nested, importedPath: [...nested.importedPath, member] };
}
if (
!t.isCallExpression(node) ||
!t.isIdentifier(node.callee, { name: "require" })
)
return undefined;
if (
resolveSemanticBindingState(state, node.callee, "require") !== undefined ||
semanticResolutionBlocked(state, node.callee, "require")
)
return undefined;
const specifier = stringValue(node.arguments[0]);
return specifier === undefined ? undefined : { specifier, importedPath: [] };
};
const mergeValues = (
values: readonly JavaScriptSemanticValue[],
): JavaScriptSemanticValue => {
@@ -0,0 +1,63 @@
import { expect, it } from "vitest";
import { collectJavaScriptExports } from "./javascriptAstFingerprint.js";
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
import { parseJavaScriptSource } from "./javascriptSourceParser.js";
const memberChain = ".next".repeat(12_000);
it("collects a 12,000-member CommonJS export path without recursion", () => {
const file = parseJavaScriptSource(`exports${memberChain}.last = 1;`);
if (file === null) throw new Error("Expected valid JavaScript");
expect(collectJavaScriptExports(file).values).toEqual([
`${"next.".repeat(12_000)}last`,
]);
});
it("preserves empty, dynamic, this, and private member path behavior", () => {
const file = parseJavaScriptSource(`
exports[""].value = 1;
exports[""] = 0;
exports[key].value = 2;
this.exports.ignored = 3;
class Example { #private = 0; read() { this.#private = 1; } }
`);
if (file === null) throw new Error("Expected valid JavaScript");
expect(collectJavaScriptExports(file).values).toEqual([
"",
".value",
"key.value",
]);
});
it("keeps left-first and outer-member-first bundler runtime matches", () => {
const source = `
(globalThis.webpackChunkLeft || globalThis.webpackChunkRight).push([[1], { 1: function() {} }]);
globalThis.webpackChunkOuter.webpackChunkInner.push([[2], { 2: function() {} }]);
`;
const analysis = analyzeJavaScriptStaticSource(source);
expect(
analysis.bundler_registrations.find(({ chunk_keys }) =>
chunk_keys.includes("1"),
)?.runtime,
).toBe("webpackChunkLeft");
expect(
analysis.bundler_registrations.find(({ chunk_keys }) =>
chunk_keys.includes("2"),
)?.runtime,
).toBe("webpackChunkInner");
});
it("analyzes a 12,000-member bundler runtime chain without recursion", () => {
const source = `globalThis.webpackChunkApp${memberChain}.push([[1], { 1: function(module) { module.exports.ok = 42; } }]);`;
const analysis = analyzeJavaScriptStaticSource(source);
expect(analysis.parse_status).toBe("complete");
expect(analysis.parse_error_count).toBe(0);
expect(analysis.bundler_registrations).toHaveLength(1);
expect(analysis.bundler_registrations[0]).toMatchObject({
bundler: "webpack",
runtime: "webpackChunkApp",
chunk_keys: ["1"],
modules: [expect.objectContaining({ exports: ["ok"] })],
});
});
@@ -73,19 +73,38 @@ export const chunkRuntime = (call: t.CallExpression): string | undefined => {
};
const findChunkRuntime = (node: t.Node): string | undefined => {
if (t.isIdentifier(node) && /(?:webpack|rspack)Chunk/iu.test(node.name))
return node.name;
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
const property = semanticStaticPropertyName(node.property, node.computed);
if (/(?:webpack|rspack)Chunk/iu.test(property)) return property;
return t.isNode(node.object) ? findChunkRuntime(node.object) : undefined;
const pending: t.Node[] = [node];
while (pending.length > 0) {
const current = pending.pop();
if (current === undefined) continue;
if (
t.isIdentifier(current) &&
/(?:webpack|rspack)Chunk/iu.test(current.name)
)
return current.name;
if (
t.isMemberExpression(current) ||
t.isOptionalMemberExpression(current)
) {
const property = semanticStaticPropertyName(
current.property,
current.computed,
);
if (/(?:webpack|rspack)Chunk/iu.test(property)) return property;
if (t.isNode(current.object)) pending.push(current.object);
continue;
}
if (t.isAssignmentExpression(current)) {
pending.push(current.right, current.left);
continue;
}
if (t.isLogicalExpression(current) || t.isBinaryExpression(current)) {
pending.push(current.right, current.left);
continue;
}
if (t.isParenthesizedExpression(current) || t.isTSAsExpression(current))
pending.push(current.expression);
}
if (t.isAssignmentExpression(node))
return findChunkRuntime(node.left) ?? findChunkRuntime(node.right);
if (t.isLogicalExpression(node) || t.isBinaryExpression(node))
return findChunkRuntime(node.left) ?? findChunkRuntime(node.right);
if (t.isParenthesizedExpression(node) || t.isTSAsExpression(node))
return findChunkRuntime(node.expression);
return undefined;
};
@@ -520,19 +539,23 @@ export const storageKind = (
};
/** Produce a dotted callee name from member syntax. */
export const calleeName = (node: t.Node): string => calleeNameAt(node);
const calleeNameAt = (node: t.Node): string => {
if (t.isIdentifier(node)) return node.name;
if (t.isImport(node)) return "import";
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
const object = t.isNode(node.object) ? calleeNameAt(node.object) : "";
// A dynamic key commits no name: `target[method]()` must not be reported as
// `target.method`, which would fabricate a runtime call shape.
const property = memberPropertyName(node);
return object === "" ? property : `${object}.${property}`;
export const calleeName = (node: t.Node): string => {
const segments: string[] = [];
while (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
// Dynamic keys retain their syntax identity instead of inventing a name.
segments.push(memberPropertyName(node));
if (!t.isNode(node.object)) break;
node = node.object;
}
return "";
const base = t.isIdentifier(node)
? node.name
: t.isImport(node)
? "import"
: "";
segments.push(base);
segments.reverse();
const first = segments.findIndex((segment) => segment !== "");
return first === -1 ? "" : segments.slice(first).join(".");
};
/** Read a member property only when its syntax commits an exact name. */
@@ -3,13 +3,13 @@ import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import { evidenceSchema, parseEvidence, type Evidence } from "./evidence.js";
import { evidenceSchema, parseEvidence, type Evidence } from "../evidence.js";
import {
createJavaScriptApplicationGraph,
javascriptApplicationGraphSchema,
type ApplicationEdge,
type ApplicationNode,
} from "./javascript/javascriptApplicationGraph.js";
} from "../javascript/javascriptApplicationGraph.js";
import {
managedArtifactInspectionSchema,
managedMemberInspectionSchema,
@@ -18,7 +18,7 @@ import {
type ManagedMemberInspection,
type ManagedNativeBoundaryInspection,
} from "./managedArtifact.js";
import type { JsonValue } from "./jsonValue.js";
import type { JsonValue } from "../jsonValue.js";
import {
assessManagedGraphOmissions,
managedGraphEvidenceCoverage,
@@ -30,8 +30,8 @@ import {
addBoundaryNodes,
addMemberNodes,
} from "./managedApplicationGraphNodes.js";
import { digestSchema } from "./../domain/digests.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const textSchema = z.string().min(1);
@@ -1,4 +1,4 @@
import type { ApplicationGraphEvidence } from "./javascript/javascriptApplicationGraph.js";
import type { ApplicationGraphEvidence } from "../javascript/javascriptApplicationGraph.js";
import type {
ManagedArtifactInspection,
ManagedMemberInspection,
@@ -4,7 +4,7 @@ import {
createJavaScriptApplicationNode,
type ApplicationGraphEvidence,
type ApplicationNode,
} from "./javascript/javascriptApplicationGraph.js";
} from "../javascript/javascriptApplicationGraph.js";
import { managedSourceCoverage } from "./managedApplicationGraphCoverage.js";
import {
type ManagedMemberInspection,
@@ -1,5 +1,5 @@
import { z } from "zod";
import { digestSchema } from "./../domain/digests.js";
import { digestSchema } from "../digests.js";
const tokenSchema = z.string().regex(/^0x[0-9a-f]{8}$/u);
const offsetSchema = z.number().int().min(0);
@@ -1,7 +1,7 @@
import { z } from "zod";
import { emptyArraySchema } from "./emptyArraySchema.js";
import { evidenceSchema } from "./evidence.js";
import { emptyArraySchema } from "../emptyArraySchema.js";
import { evidenceSchema } from "../evidence.js";
import {
cliMetadataGuidSchema,
type ManagedMemberInspection,
@@ -18,8 +18,8 @@ import {
buildMethodItems,
} from "./managedMemberComparisonItems.js";
import { keyMembers, sha256 } from "./managedMemberComparisonMatch.js";
import { digestSchema } from "./../domain/digests.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const tokenSchema = z.string().regex(/^0x[0-9a-f]{8}$/u);
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { parseEvidence } from "./evidence.js";
import { parseEvidence } from "../evidence.js";
import {
managedMemberInspectionSchema,
type ManagedMemberInspection,
@@ -11,7 +11,7 @@ import type {
ManagedMemberComparisonResult,
ManagedMemberComparisonSide,
} from "./managedMemberComparison.js";
import type { JsonValue } from "./jsonValue.js";
import type { JsonValue } from "../jsonValue.js";
export const sha256 = (value: JsonValue): string => {
const serialized = canonicalize(value);
@@ -2,12 +2,12 @@ import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { parseEvidence } from "./evidence.js";
import { parseEvidence } from "../evidence.js";
import {
managedNativeBoundaryInspectionSchema,
type ManagedNativeBoundaryInspection,
} from "./managedArtifact.js";
import type { JsonValue } from "./jsonValue.js";
import type { JsonValue } from "../jsonValue.js";
import {
managedNativeVerificationResultSchema,
type ManagedNativeVerificationInput,
@@ -3,11 +3,11 @@ import { basename } from "node:path";
import canonicalize from "canonicalize";
import { parseEvidence } from "./evidence.js";
import { functionDossierSchema } from "./hopperValues.js";
import { inspectMachoSchema } from "./nativeInspection.js";
import { parseEvidence } from "../evidence.js";
import { functionDossierSchema } from "../hopperValues.js";
import { inspectMachoSchema } from "../nativeInspection.js";
import type { ManagedNativeBoundaryInspection } from "./managedArtifact.js";
import type { JsonValue } from "./jsonValue.js";
import type { JsonValue } from "../jsonValue.js";
import {
pinvokeVerificationSchema,
type ManagedNativeVerificationInput,
@@ -1,10 +1,10 @@
import { z } from "zod";
import { emptyArraySchema } from "./emptyArraySchema.js";
import { evidenceSchema } from "./evidence.js";
import { emptyArraySchema } from "../emptyArraySchema.js";
import { evidenceSchema } from "../evidence.js";
import { cliMetadataGuidSchema } from "./managedArtifact.js";
import { digestSchema } from "./../domain/digests.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const tokenSchema = z.string().regex(/^0x[0-9a-f]{8}$/u);
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { createEvidence } from "./evidence.js";
import { createEvidence } from "../evidence.js";
import { managedReconstructionImportInputSchema } from "./managedReconstruction.js";
describe("managed reconstruction import input", () => {
@@ -3,15 +3,15 @@ import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import { evidenceSchema, parseEvidence } from "./evidence.js";
import { evidenceSchema, parseEvidence } from "../evidence.js";
import {
cliMetadataGuidSchema,
managedMemberInspectionSchema,
type ManagedMemberInspection,
} from "./managedArtifact.js";
import type { JsonValue } from "./jsonValue.js";
import { digestSchema } from "./../domain/digests.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
import type { JsonValue } from "../jsonValue.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const tokenSchema = z.string().regex(/^0x[0-9a-f]{8}$/u);
+4 -1
View File
@@ -8,7 +8,7 @@ import {
import {
buildInterfaceBuilderAnalysis,
interfaceBuilderLimitsSchema,
} from "./interfaceBuilderGraph.js";
} from "./apple/interfaceBuilderGraph.js";
const evidence = [
{
@@ -166,6 +166,7 @@ describe("Interface Builder dispatch joins", () => {
const joined = joinInterfaceBuilderDispatch(ui.graph, {
objc_classes: [],
objc_protocols: [],
objc_categories: [],
swift_decls: [],
objc_ivars: [],
objc_protocol_records: [],
@@ -227,6 +228,7 @@ describe("Interface Builder dispatch joins", () => {
const metadata = {
objc_classes: [],
objc_protocols: [],
objc_categories: [],
swift_decls: [],
objc_ivars: [],
objc_protocol_records: [],
@@ -304,6 +306,7 @@ describe("placeholder dispatch joins", () => {
const joined = joinInterfaceBuilderDispatch(ui.graph, {
objc_classes: [],
objc_protocols: [],
objc_categories: [],
swift_decls: [],
objc_ivars: [],
objc_protocol_records: [],
+18
View File
@@ -156,6 +156,8 @@ export const objcDispatchImplementationSchema = z.strictObject({
selector: z.string().min(1),
method_type: z.enum(["instance", "class"]),
implementation_address: z.string().nullable(),
/** Category that adds this method, when it is not defined by the class itself. */
category: z.string().nullable().optional(),
location: nativeMetadataLocationSchema,
decode: nativeMetadataDecodeSchema,
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
@@ -164,6 +166,21 @@ export type ObjcDispatchImplementation = z.infer<
typeof objcDispatchImplementationSchema
>;
/** Objective-C category: methods, protocols and properties added to a class. */
export const objcCategorySchema = z.strictObject({
name: z.string().min(1),
/** Extended class; external classes come from the category's bind symbol. */
class_name: z.string().min(1).nullable(),
class_source: z.enum(["local", "external", "unresolved"]),
instance_methods: z.array(z.string()),
class_methods: z.array(z.string()),
protocols: z.array(z.string()),
properties: z.array(objcPropertySchema),
location: nativeMetadataLocationSchema,
decode: nativeMetadataDecodeSchema,
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
});
/** Swift protocol conformance and its associated witness-table location. */
export const swiftConformanceSchema = z.strictObject({
type_name: z.string().min(1),
@@ -279,6 +296,7 @@ export type DbSaveResult = z.infer<typeof dbSaveResultSchema>;
export const objcSwiftMetadataSchema = z.strictObject({
objc_classes: z.array(objcClassSchema).default([]),
objc_protocols: z.array(objcProtocolSchema).default([]),
objc_categories: z.array(objcCategorySchema).default([]),
swift_decls: z.array(swiftDeclSchema).default([]),
objc_ivars: z.array(objcIvarSchema).default([]),
objc_protocol_records: z.array(objcProtocolRecordSchema).default([]),
+31 -7
View File
@@ -28,13 +28,37 @@ describe("direct process scenarios", () => {
});
it("rejects malformed environment names and adapter-reserved identity", () => {
for (const name of ["", "KEY=VALUE", "KEY\0VALUE", "REA_PROCESS_RUN_ID"])
expect(
processScenarioSchema.safeParse({
executable: "node",
environment: { [name]: "value" },
}).success,
).toBe(false);
for (const name of ["", "KEY=VALUE", "KEY\0VALUE", "REA_PROCESS_RUN_ID"]) {
const result = processScenarioSchema.safeParse({
executable: "node",
environment: { [name]: "value" },
});
expect(result.success).toBe(false);
if (name === "" && !result.success) {
const invalidKey = result.error.issues[0];
expect(invalidKey?.code).toBe("invalid_key");
if (invalidKey?.code === "invalid_key") {
expect(invalidKey.issues[0]?.message).toBe(
"Environment names must not be empty",
);
}
}
if (name === "REA_PROCESS_RUN_ID" && !result.success) {
const invalidKey = result.error.issues[0];
expect(invalidKey?.code).toBe("invalid_key");
if (invalidKey?.code === "invalid_key") {
expect(invalidKey.issues[0]?.message).toBe(
"REA_PROCESS_RUN_ID is reserved by the process adapter",
);
}
}
}
expect(
processScenarioSchema.safeParse({
executable: "node",
environment: { "REA_PROCESS_RUN_ID\n": "caller-value" },
}).success,
).toBe(true);
});
it("keeps bounded capture controls and ordered scheduled interaction", () => {

Some files were not shown because too many files have changed in this diff Show More