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
+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);
@@ -1,43 +0,0 @@
import { describe, expect, it } from "vitest";
import { collectInterfaceBuilderResourceKeys } from "./AppleAssetCatalogAnalysis.js";
describe("Apple asset catalog application workflow", () => {
it("joins only explicit resource-key fields with archive provenance", () => {
expect(
collectInterfaceBuilderResourceKeys([
{
id: "ib:Main.nib:object:2",
kind: "resource",
name: "Decorative image",
attributes: {
imageName: "Toolbar",
title: "not-an-asset-key",
image: 42,
},
evidence: [
{
artifact_path: "Contents/Resources/Main.nib",
artifact_sha256: "d".repeat(64),
},
],
},
{
id: "ib:Main.nib:object:3",
kind: "control",
name: "Toolbar",
attributes: { title: "not-an-asset-key" },
evidence: [],
},
]),
).toEqual([
{
sourceNodeId: "ib:Main.nib:object:2",
sourcePath: "Contents/Resources/Main.nib",
sourceArchiveSha256: "d".repeat(64),
field: "imageName",
key: "Toolbar",
},
]);
});
});
@@ -1,267 +0,0 @@
import { createHash } from "node:crypto";
import { lstat } from "node:fs/promises";
import { DirectoryArtifactReader } from "../artifacts/DirectoryArtifactReader.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import { analyzeInterfaceBuilderBundle } from "./InterfaceBuilderAnalysis.js";
import {
appleAssetCatalogInputSchema,
parseAppleAssetCatalogRecords,
projectAppleAssetCatalogPage,
} from "../domain/appleAssetCatalog.js";
import { execFileOutput } from "../process/ExecFileOutput.js";
const ASSETUTIL = "/usr/bin/assetutil";
const MAX_CATALOG_BYTES = 64 * 1024 * 1024;
const MAX_TOTAL_METADATA_BYTES = 64 * 1024 * 1024;
const RESOURCE_KEY_FIELDS = new Set([
"image",
"imageName",
"image_name",
"resourceName",
"resource_name",
"assetName",
"asset_name",
"UIImageName",
"NSImageName",
]);
/** Inspect compiled asset catalog metadata without extracting rendition bytes. */
export const analyzeAppleAssetCatalogs = async (input: {
readonly bundlePath: string;
readonly targetSha256: string;
readonly page?: unknown;
readonly signal?: AbortSignal;
readonly runAssetUtil?: (
path: string,
signal?: AbortSignal,
) => Promise<string>;
}) => {
if (process.platform !== "darwin" && input.runAssetUtil === undefined)
throw new ArtifactReaderFailure(
"unavailable",
"Apple asset catalog inspection requires macOS assetutil",
);
const page = appleAssetCatalogInputSchema.parse(input.page ?? {});
const reader = new DirectoryArtifactReader(input.bundlePath);
const catalogs: {
path: string;
sha256: string;
records: ReturnType<typeof parseAppleAssetCatalogRecords>;
}[] = [];
let totalMetadataBytes = 0;
try {
for await (const entry of reader.entries(input.signal)) {
if (entry.kind !== "file" || !entry.path.endsWith("Assets.car")) continue;
const inspected = await inspectAssetCatalogEntry({
reader,
entry,
runAssetUtil: input.runAssetUtil ?? runAssetUtil,
...(input.signal === undefined ? {} : { signal: input.signal }),
});
totalMetadataBytes += inspected.metadataBytes;
if (totalMetadataBytes > MAX_TOTAL_METADATA_BYTES)
throw new ArtifactReaderFailure(
"limit",
`Combined asset catalog metadata exceeds ${MAX_TOTAL_METADATA_BYTES} bytes`,
);
catalogs.push(inspected.catalog);
}
} finally {
await reader.close();
}
if (catalogs.length === 0)
throw new ArtifactReaderFailure(
"unavailable",
"No compiled Assets.car catalogs were found in the app bundle",
);
const interfaceBuilder = await analyzeInterfaceBuilderBundle({
bundlePath: input.bundlePath,
targetSha256: input.targetSha256,
...(input.signal === undefined ? {} : { signal: input.signal }),
});
const resourceReferences = collectInterfaceBuilderResourceKeys(
interfaceBuilder.graph.nodes,
);
const result = projectAppleAssetCatalogPage({
targetSha256: input.targetSha256,
catalogs,
offset: page.offset,
limit: page.limit,
resourceReferences,
});
return {
...result,
limitations: [
...result.limitations,
"Exact resource-key joins use only recognized image or asset key fields on decoded Interface Builder resource objects; other archive resource references are not inferred.",
...(interfaceBuilder.graph.truncated
? [
"Interface Builder resource-key joins may be incomplete because the decoded UI graph was truncated.",
]
: []),
],
};
};
const inspectAssetCatalogEntry = async (input: {
readonly reader: DirectoryArtifactReader;
readonly entry: import("../artifacts/ArtifactReader.js").ArtifactEntry;
readonly runAssetUtil: (
path: string,
signal?: AbortSignal,
) => Promise<string>;
readonly signal?: AbortSignal;
}) => {
const { entry, reader, signal } = input;
const sha256 = await digestBounded(reader, entry, signal);
const before = await lstat(entry.adapterKey);
if (
entry.sourceIdentity === undefined ||
before.dev !== entry.sourceIdentity.device ||
before.ino !== entry.sourceIdentity.inode
)
throw new ArtifactReaderFailure(
"integrity",
`Asset catalog changed before inspection: ${entry.path}`,
);
const output = await input.runAssetUtil(entry.adapterKey, signal);
const after = await lstat(entry.adapterKey);
if (
before.dev !== after.dev ||
before.ino !== after.ino ||
before.size !== after.size ||
(await digestBounded(reader, entry, signal)) !== sha256
)
throw new ArtifactReaderFailure(
"integrity",
`Asset catalog changed during inspection: ${entry.path}`,
);
let parsed: unknown;
try {
parsed = JSON.parse(output);
} catch (cause: unknown) {
throw new ArtifactReaderFailure(
"format",
`assetutil returned invalid JSON for ${entry.path}`,
{ cause },
);
}
try {
return {
catalog: {
path: entry.path,
sha256,
records: parseAppleAssetCatalogRecords(parsed),
},
metadataBytes: Buffer.byteLength(output, "utf8"),
};
} catch (cause: unknown) {
throw new ArtifactReaderFailure(
"format",
`assetutil returned an unsupported record for ${entry.path}`,
{ cause },
);
}
};
/** Return only explicit image or asset fields from decoded resource objects. */
export const collectInterfaceBuilderResourceKeys = (
nodes: readonly {
readonly id: string;
readonly kind: string;
readonly name?: string;
readonly attributes: Readonly<Record<string, unknown>>;
readonly evidence: readonly {
readonly artifact_path: string | null;
readonly artifact_sha256: string | null;
}[];
}[],
) =>
nodes.flatMap((node) => {
const source = node.evidence.find(
(item) => item.artifact_path !== null && item.artifact_sha256 !== null,
);
const sourcePath = source?.artifact_path;
const sourceArchiveSha256 = source?.artifact_sha256;
if (sourcePath == null || sourceArchiveSha256 == null) return [];
return Object.entries(node.attributes).flatMap(([field, value]) =>
RESOURCE_KEY_FIELDS.has(field) &&
typeof value === "string" &&
value.length > 0
? [
{
sourceNodeId: node.id,
sourcePath,
sourceArchiveSha256,
field,
key: value,
},
]
: [],
);
});
const runAssetUtil = async (
path: string,
signal?: AbortSignal,
): Promise<string> => {
try {
return (
await execFileOutput(ASSETUTIL, ["--info", path], {
timeout: 60_000,
maxBuffer: MAX_CATALOG_BYTES,
...(signal === undefined ? {} : { signal }),
})
).stdout;
} catch (cause: unknown) {
if (signal?.aborted === true)
throw new ArtifactReaderFailure(
"cancelled",
"Asset catalog inspection cancelled",
);
const code =
typeof cause === "object" && cause !== null && "code" in cause
? cause.code
: undefined;
throw new ArtifactReaderFailure(
code === "ENOENT"
? "unavailable"
: code === "ETIMEDOUT" || code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER"
? "limit"
: "io",
`assetutil failed${code === undefined ? "" : ` (${String(code)})`}`,
{ cause },
);
}
};
const digestBounded = async (
reader: DirectoryArtifactReader,
entry: import("../artifacts/ArtifactReader.js").ArtifactEntry,
signal?: AbortSignal,
): Promise<string> => {
if (entry.declaredSize === null || entry.declaredSize > MAX_CATALOG_BYTES)
throw new ArtifactReaderFailure(
"limit",
`Asset catalog exceeds ${MAX_CATALOG_BYTES} bytes: ${entry.path}`,
);
const stream = await reader.open(entry, signal);
const hash = createHash("sha256");
let length = 0;
for await (const chunk of stream) {
if (signal?.aborted === true)
throw new ArtifactReaderFailure(
"cancelled",
"Asset catalog inspection cancelled",
);
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
length += bytes.length;
if (length > MAX_CATALOG_BYTES)
throw new ArtifactReaderFailure(
"limit",
`Asset catalog exceeds byte limit: ${entry.path}`,
);
hash.update(bytes);
}
return hash.digest("hex");
};
+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";
-401
View File
@@ -1,401 +0,0 @@
import { createHash } from "node:crypto";
import { parseBinary } from "plist";
import { DirectoryArtifactReader } from "../artifacts/DirectoryArtifactReader.js";
import {
omittedPrototypeKeysLimitation,
parseXmlPropertyList,
} from "../domain/propertyListKeys.js";
import {
decodeNibArchive,
type NibArchiveDocument,
} from "../artifacts/NibArchive.js";
import type { ArtifactEntry } from "../artifacts/ArtifactReader.js";
import {
buildInterfaceBuilderAnalysis,
interfaceBuilderLimitsSchema,
type InterfaceBuilderDocumentInput,
} from "../domain/interfaceBuilderGraph.js";
import {
mergeNibHierarchies,
projectNibViewHierarchy,
type NibHierarchyNode,
} from "./NibViewHierarchy.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
const MAX_DOCUMENT_BYTES = 64 * 1024 * 1024;
/** Decode compiled Interface Builder archives from a local app bundle. */
export const analyzeInterfaceBuilderBundle = async (input: {
readonly bundlePath: string;
readonly targetSha256: string;
readonly limits?: unknown;
readonly signal?: AbortSignal;
}) => {
const limits = interfaceBuilderLimitsSchema.parse(input.limits ?? {});
const reader = new DirectoryArtifactReader(input.bundlePath);
const documents: InterfaceBuilderDocumentInput[] = [];
const invalid: string[] = [];
const incompleteHierarchies = new Map<string, number>();
const prototypeKeyOmissions = new Map<string, number>();
let omitted = 0;
let attempted = 0;
try {
for await (const entry of reader.entries(input.signal)) {
if (entry.kind !== "file" || !isInterfaceBuilderArchive(entry.path))
continue;
if (attempted >= limits.max_documents) {
omitted += 1;
continue;
}
attempted += 1;
try {
const bytes = await readEntry(reader, entry, input.signal);
const nib =
bytes.subarray(0, 10).toString("ascii") === "NIBArchive"
? projectNibArchive(decodeNibArchive(bytes))
: null;
const { value: raw, omittedPrototypeKeys } =
nib === null
? decodePlist(bytes)
: { value: nib.raw, omittedPrototypeKeys: 0 };
if (nib !== null && nib.omitted > 0)
incompleteHierarchies.set(entry.path, nib.omitted);
if (omittedPrototypeKeys > 0)
prototypeKeyOmissions.set(entry.path, omittedPrototypeKeys);
const documentHash = createHash("sha256").update(bytes).digest("hex");
documents.push({
relativePath: entry.path,
archiveSha256: documentHash,
documentKind: entry.path.includes(".storyboardc/")
? "storyboard_scene"
: "nib",
raw,
});
} catch (cause: unknown) {
if (input.signal?.aborted === true) throw cause;
invalid.push(
`${entry.path}: ${cause instanceof Error ? cause.message : "archive decode failed"}`,
);
}
}
} finally {
await reader.close();
}
const result = buildInterfaceBuilderAnalysis({
targetSha256: input.targetSha256,
toolVersion: "rea-interface-builder/1",
documents,
limits,
});
return finalizeHierarchyCoverage(result, {
incompleteHierarchies,
prototypeKeyOmissions,
invalid,
attempted,
omitted,
});
};
const finalizeHierarchyCoverage = (
result: ReturnType<typeof buildInterfaceBuilderAnalysis>,
counts: {
incompleteHierarchies: ReadonlyMap<string, number>;
prototypeKeyOmissions: ReadonlyMap<string, number>;
invalid: readonly string[];
attempted: number;
omitted: number;
},
) => {
const { incompleteHierarchies, prototypeKeyOmissions, invalid } = counts;
const archiveDecodePartial =
invalid.length > 0 || prototypeKeyOmissions.size > 0;
return {
...result,
documents: result.documents.map((document) => ({
...document,
hierarchy_complete:
document.hierarchy_complete &&
!incompleteHierarchies.has(document.relative_path),
})),
graph: {
...result.graph,
coverage: [
...result.graph.coverage.map((facet) => {
const omitted = incompleteHierarchies.get(
facet.facet.replace(/^hierarchy:/u, ""),
);
return facet.facet.startsWith("hierarchy:") && omitted !== undefined
? {
...facet,
status: "partial" as const,
reason: "serialized_view_hierarchy_incomplete",
omitted: facet.omitted + omitted,
}
: facet;
}),
{
facet: "archive_decode",
status: archiveDecodePartial
? ("partial" as const)
: ("complete" as const),
reason:
invalid.length > 0
? "one_or_more_archives_invalid"
: prototypeKeyOmissions.size > 0
? "dictionary_entries_omitted"
: null,
examined: counts.attempted,
omitted: counts.omitted,
},
],
truncated:
result.graph.truncated ||
counts.omitted > 0 ||
archiveDecodePartial ||
incompleteHierarchies.size > 0,
},
limitations: [
...result.limitations,
"Compiled Interface Builder archives are private serialized object graphs. The decoder reports only recognized keyed-archive objects and connections; unrecognized object classes and fields remain unknown.",
...(incompleteHierarchies.size === 0
? []
: [
"Some serialized hierarchy links could not be projected within the bounded hierarchy; their parentage remains unknown.",
]),
...(invalid.length === 0
? []
: [
`Some Interface Builder archives could not be decoded: ${invalid.slice(0, 16).join("; ")}`,
]),
...[...prototypeKeyOmissions].map(
([path, count]) => `${path}: ${omittedPrototypeKeysLimitation(count)}`,
),
],
};
};
/** Project decoded NIB records into the same bounded graph input as ibtool. */
const projectNibArchive = (archive: NibArchiveDocument) => {
const byId = new Map(archive.objects.map((object) => [object.id, object]));
const dereference = (value: JsonValue | undefined): JsonValue | undefined => {
if (typeof value !== "object" || value === null || Array.isArray(value))
return value;
const ref = value.$nib_object_ref;
if (typeof ref !== "number") return value;
const target = byId.get(ref);
if (target === undefined) return undefined;
if (target.class_name.replace(/\0+$/u, "") === "NSString") {
const data = target.values["NS.bytes"];
if (typeof data === "object" && data !== null && !Array.isArray(data)) {
const encoded = data.$nib_data_base64;
if (typeof encoded === "string")
return Buffer.from(encoded, "base64").toString("utf8");
}
}
return { objectID: String(ref) };
};
const referencedString = (value: JsonValue | undefined): string | null => {
if (typeof value !== "object" || value === null || Array.isArray(value))
return null;
const ref = value.$nib_object_ref;
if (typeof ref !== "number") return null;
const target = byId.get(ref);
const data = target?.values["NS.bytes"];
if (target?.class_name.replace(/\0+$/u, "") !== "NSString") return null;
if (typeof data !== "object" || data === null || Array.isArray(data))
return null;
const encoded = data.$nib_data_base64;
return typeof encoded === "string"
? Buffer.from(encoded, "base64").toString("utf8")
: null;
};
const runtimeClass = (objectId: number): string | null => {
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)
: 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(
name,
);
})
.map((object) => {
const className =
runtimeClass(object.id) ?? object.class_name.replace(/\0+$/u, "");
const strings = Object.entries(object.values).flatMap(
([key, value]) => {
const resolved = dereference(value);
return typeof resolved === "string" ? [[key, resolved]] : [];
},
);
const name =
strings.find(([key]) =>
/(?:title|label|identifier|accessibility|name|contents)/iu.test(
key ?? "",
),
)?.[1] ?? className;
return [
String(object.id),
{
customClass: className,
label: name,
objectID: String(object.id),
nibValues: Object.fromEntries(
Object.entries(object.values).map(([key, value]) => [
key,
dereference(value) ?? null,
]),
),
},
];
}),
);
const connections: Record<string, JsonValue[]> = {};
const hierarchy: NibHierarchyNode[] = [];
const reference = (value: JsonValue | undefined): number | null => {
if (typeof value !== "object" || value === null || Array.isArray(value))
return null;
return typeof value.$nib_object_ref === "number"
? value.$nib_object_ref
: null;
};
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),
});
}
}
let hierarchyOmitted = 0;
const hierarchyFor = (
objectId: number,
seen: Set<number>,
depth: number,
): NibHierarchyNode | null => {
if (depth > 32 || seen.has(objectId)) {
hierarchyOmitted += 1;
return null;
}
const object = byId.get(objectId);
if (object === undefined) {
hierarchyOmitted += 1;
return null;
}
const nextSeen = new Set(seen).add(objectId);
const children: NibHierarchyNode[] = [];
for (const [key, value] of Object.entries(object.values)) {
if (!/(?:subviews|contentview|childviewcontrollers|view)$/iu.test(key))
continue;
const direct = reference(value);
if (direct === null) continue;
const target = byId.get(direct);
if (target === undefined) {
hierarchyOmitted += 1;
continue;
}
if (/array|set/iu.test(target.class_name)) {
for (const candidate of Object.values(target.values)) {
const child = reference(candidate);
const nested =
child === null ? null : hierarchyFor(child, nextSeen, depth + 1);
if (nested !== null) children.push(nested);
}
} else {
const nested = hierarchyFor(direct, nextSeen, depth + 1);
if (nested !== null) children.push(nested);
}
}
return { objectID: String(objectId), children };
};
const ibData = archive.objects.find(
({ class_name }) => class_name.replace(/\0+$/u, "") === "NSIBObjectData",
);
const rootId = reference(ibData?.values.NSRoot);
const hierarchyRoots = rootId === null ? [] : [rootId];
for (const hierarchyRoot of hierarchyRoots) {
const root = hierarchyFor(hierarchyRoot, new Set(), 0);
if (root !== null) hierarchy.push(root);
}
const viewHierarchy = projectNibViewHierarchy(
archive.objects,
new Set(Object.keys(objects).map(Number)),
);
const merged = mergeNibHierarchies(hierarchy, viewHierarchy.hierarchy ?? []);
return {
omitted: viewHierarchy.omitted + hierarchyOmitted + merged.omitted,
raw: jsonValueSchema.parse({
"com.apple.ibtool.document.objects": objects,
"com.apple.ibtool.document.connections": connections,
"com.apple.ibtool.document.hierarchy": merged.hierarchy,
"com.apple.ibtool.document.classes": Object.fromEntries(
archive.classes.map((name) => [name.replace(/\0+$/u, ""), {}]),
),
}),
};
};
const isInterfaceBuilderArchive = (path: string): boolean => {
const lower = path.toLowerCase();
return lower.endsWith(".nib") || lower.endsWith("/objects.nib");
};
const readEntry = async (
reader: DirectoryArtifactReader,
entry: ArtifactEntry,
signal?: AbortSignal,
): Promise<Buffer> => {
if (entry.declaredSize !== null && entry.declaredSize > MAX_DOCUMENT_BYTES)
throw new RangeError(
"archive exceeds the 64 MiB per-document decode limit",
);
const stream = await reader.open(entry, signal);
const chunks: Buffer[] = [];
let length = 0;
for await (const chunk of stream) {
const bytes = Buffer.isBuffer(chunk)
? chunk
: Buffer.from(chunk as Uint8Array);
length += bytes.length;
if (length > MAX_DOCUMENT_BYTES) {
stream.destroy();
throw new RangeError(
"archive exceeded the 64 MiB per-document decode limit",
);
}
chunks.push(bytes);
}
return Buffer.concat(chunks, length);
};
const decodePlist = (
bytes: Buffer,
): { readonly value: JsonValue; readonly omittedPrototypeKeys: number } => {
const { value, omittedPrototypeKeys } =
bytes.subarray(0, 8).toString("ascii") === "bplist00"
? { value: parseBinary(bytes), omittedPrototypeKeys: 0 }
: parseXmlPropertyList(bytes.toString("utf8"));
return { value: jsonValueSchema.parse(value), omittedPrototypeKeys };
};
+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,
-189
View File
@@ -1,189 +0,0 @@
import { describe, expect, it } from "vitest";
import {
mergeNibHierarchies,
projectNibViewHierarchy,
} from "./NibViewHierarchy.js";
const object = (id: number, parent?: number) => ({
id,
class_name: "NSView",
values:
parent === undefined ? {} : { NSSuperview: { $nib_object_ref: parent } },
});
describe("serialized NIB view hierarchy bounds", () => {
it("leaves archives without superview links to the legacy projection", () => {
expect(projectNibViewHierarchy([object(0)], new Set([0]))).toEqual({
hierarchy: null,
omitted: 0,
});
});
it("uses the serialized parent direction and retains all sibling links", () => {
expect(
projectNibViewHierarchy(
[object(0), object(1, 0), object(2, 0)],
new Set([0, 1, 2]),
),
).toEqual({
hierarchy: [
{
objectID: "0",
children: [
{ objectID: "1", children: [] },
{ objectID: "2", children: [] },
],
},
],
omitted: 0,
});
});
it("reports missing parents without inventing parentage", () => {
expect(projectNibViewHierarchy([object(0, 99)], new Set([0]))).toEqual({
hierarchy: [],
omitted: 1,
});
});
it("reports a missing encoded window content view as incomplete", () => {
expect(
projectNibViewHierarchy(
[
{
id: 0,
class_name: "NSWindowTemplate",
values: { NSWindowView: { $nib_object_ref: 99 } },
},
],
new Set([0]),
),
).toEqual({ hierarchy: [{ objectID: "0", children: [] }], omitted: 1 });
});
it("marks unsupported serialized parent values as incomplete", () => {
expect(
projectNibViewHierarchy(
[{ id: 0, class_name: "NSView", values: { NSSuperview: "unknown" } }],
new Set([0]),
),
).toEqual({ hierarchy: null, omitted: 1 });
});
it("reports cyclic and self-referential parentage as incomplete", () => {
expect(
projectNibViewHierarchy(
[object(0, 1), object(1, 0), object(2, 2)],
new Set([0, 1, 2]),
),
).toEqual({
hierarchy: [],
omitted: 3,
});
});
it("does not project children whose parent was not retained", () => {
expect(
projectNibViewHierarchy([object(0), object(1, 0)], new Set([1])),
).toEqual({
hierarchy: [],
omitted: 1,
});
});
it("reports nodes beyond the depth bound instead of claiming complete coverage", () => {
const objects = Array.from({ length: 132 }, (_, id) =>
object(id, id === 0 ? undefined : id - 1),
);
expect(
projectNibViewHierarchy(objects, new Set(objects.map(({ id }) => id)))
.omitted,
).toBe(3);
});
it("reports nodes beyond the record bound", () => {
const objects = Array.from({ length: 20_002 }, (_, id) =>
object(id, id === 0 ? undefined : 0),
);
expect(
projectNibViewHierarchy(objects, new Set(objects.map(({ id }) => id)))
.omitted,
).toBe(2);
});
});
describe("legacy NIB hierarchy preservation", () => {
it("keeps encoded window parents while merging shared views only once", () => {
const legacy = [
{
objectID: "window",
children: [
{ objectID: "view", children: [{ objectID: "first", children: [] }] },
],
},
];
const recovered = [
{
objectID: "view",
children: [
{ objectID: "first", children: [] },
{ objectID: "second", children: [] },
],
},
];
expect(mergeNibHierarchies(legacy, recovered).hierarchy).toEqual([
{
objectID: "window",
children: [
{
objectID: "view",
children: [
{ objectID: "first", children: [] },
{ objectID: "second", children: [] },
],
},
],
},
]);
});
it("moves an existing root under its encoded parent without duplicate visits", () => {
expect(
mergeNibHierarchies(
[{ objectID: "child", children: [] }],
[
{
objectID: "parent",
children: [{ objectID: "child", children: [] }],
},
],
),
).toEqual({
hierarchy: [
{ objectID: "parent", children: [{ objectID: "child", children: [] }] },
],
omitted: 0,
});
});
it("reports conflicting encoded parents rather than dropping a link silently", () => {
const legacy = [
{ objectID: "first", children: [{ objectID: "child", children: [] }] },
];
const recovered = [
{ objectID: "second", children: [{ objectID: "child", children: [] }] },
];
expect(mergeNibHierarchies(legacy, recovered).omitted).toBe(1);
});
it("does not introduce a cycle when moving an existing root", () => {
const legacy = [
{ objectID: "child", children: [{ objectID: "parent", children: [] }] },
];
const recovered = [
{ objectID: "parent", children: [{ objectID: "child", children: [] }] },
];
expect(mergeNibHierarchies(legacy, recovered)).toEqual({
hierarchy: legacy,
omitted: 1,
});
});
});
-176
View File
@@ -1,176 +0,0 @@
import type { NibArchiveDocument } from "../artifacts/NibArchive.js";
import type { JsonValue } from "../domain/jsonValue.js";
export type NibHierarchyNode = {
objectID: string;
children: NibHierarchyNode[];
};
/** Project encoded view parents; archive owners are not inferred view parents. */
export const projectNibViewHierarchy = (
objects: NibArchiveDocument["objects"],
retainedIds: ReadonlySet<number>,
) => {
const { parents, involved, invalid } = collectNibParents(
objects,
retainedIds,
);
if (parents.size === 0) return { hierarchy: null, omitted: invalid };
const children = new Map<number, number[]>();
for (const [child, parent] of parents) {
if (!retainedIds.has(parent) || !retainedIds.has(child)) continue;
const siblings = children.get(parent) ?? [];
siblings.push(child);
children.set(parent, siblings);
}
const roots: NibHierarchyNode[] = [];
const pending: { id: number; depth: number; output: NibHierarchyNode[] }[] =
[];
for (const id of involved)
if (!parents.has(id)) pending.push({ id, depth: 0, output: roots });
const visited = new Set<number>();
while (pending.length > 0) {
const item = pending.pop();
if (item === undefined) break;
if (visited.has(item.id) || item.depth > 128 || visited.size >= 20_000)
continue;
visited.add(item.id);
const node: NibHierarchyNode = { objectID: String(item.id), children: [] };
item.output.push(node);
for (const child of [...(children.get(item.id) ?? [])].reverse())
pending.push({ id: child, depth: item.depth + 1, output: node.children });
}
return {
hierarchy: roots,
omitted: involved.size - visited.size + invalid,
};
};
/** Add encoded parent links once; conflicting legacy parents remain unknown. */
export const mergeNibHierarchies = (
legacy: NibHierarchyNode[],
recovered: NibHierarchyNode[],
) => {
const existing = new Map<string, NibHierarchyNode>();
const owners = new Map<string, NibHierarchyNode[]>();
const parents = new Map<string, string>();
const pending = legacy.map((node) => ({
node,
output: legacy,
parent: null as string | null,
}));
while (pending.length > 0) {
const entry = pending.pop();
if (entry === undefined || existing.has(entry.node.objectID)) continue;
existing.set(entry.node.objectID, entry.node);
owners.set(entry.node.objectID, entry.output);
if (entry.parent !== null) parents.set(entry.node.objectID, entry.parent);
pending.push(
...entry.node.children.map((node) => ({
node,
output: entry.node.children,
parent: entry.node.objectID,
})),
);
}
let omitted = 0;
const additions = recovered.map((node) => ({
node,
output: legacy,
parent: null as string | null,
}));
while (additions.length > 0) {
const entry = additions.pop();
if (entry === undefined) break;
let target = existing.get(entry.node.objectID);
if (target === undefined) {
target = { objectID: entry.node.objectID, children: [] };
existing.set(target.objectID, target);
entry.output.push(target);
owners.set(target.objectID, entry.output);
if (entry.parent !== null) parents.set(target.objectID, entry.parent);
} else if (
entry.parent !== null &&
owners.get(target.objectID) !== entry.output
) {
const owner = owners.get(target.objectID);
if (
owner !== legacy ||
wouldCycle(target.objectID, entry.parent, parents)
) {
omitted += 1;
} else {
owner.splice(owner.indexOf(target), 1);
entry.output.push(target);
owners.set(target.objectID, entry.output);
parents.set(target.objectID, entry.parent);
}
}
for (const node of [...entry.node.children].reverse())
additions.push({
node,
output: target.children,
parent: target.objectID,
});
}
return { hierarchy: legacy, omitted };
};
const wouldCycle = (
child: string,
parent: string,
parents: ReadonlyMap<string, string>,
): boolean => {
const seen = new Set<string>();
let current: string | undefined = parent;
while (current !== undefined && !seen.has(current)) {
if (current === child) return true;
seen.add(current);
current = parents.get(current);
}
return false;
};
const reference = (value: JsonValue | undefined): number | null => {
if (typeof value !== "object" || value === null || Array.isArray(value))
return null;
return typeof value.$nib_object_ref === "number"
? value.$nib_object_ref
: null;
};
const collectNibParents = (
objects: NibArchiveDocument["objects"],
retainedIds: ReadonlySet<number>,
) => {
const parents = new Map<number, number>();
const involved = new Set<number>();
let invalid = 0;
for (const object of objects) {
if (!retainedIds.has(object.id)) continue;
const child = reference(object.values.NSWindowView);
if (
object.class_name.replace(/\0+$/u, "") === "NSWindowTemplate" &&
invalidReference(object.values.NSWindowView)
)
invalid += 1;
if (
object.class_name.replace(/\0+$/u, "") === "NSWindowTemplate" &&
child !== null
) {
parents.set(child, object.id);
involved.add(object.id);
involved.add(child);
}
const parent = reference(object.values.NSSuperview);
if (invalidReference(object.values.NSSuperview)) invalid += 1;
if (parent === null) continue;
parents.set(object.id, parent);
involved.add(object.id);
if (retainedIds.has(parent)) involved.add(parent);
}
return { parents, involved, invalid };
};
const invalidReference = (value: JsonValue | undefined): boolean =>
value !== undefined && value !== null && reference(value) === null;
+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;