feat(native): add inspection primitives, dispatch traces and approved UI observation (#500)

* fix(hopper): normalize string-backed addresses and update verification

* feat(native): add inspection primitives, dispatch traces and approved UI observation

* test: prioritize real artifact E2E and captured golden regressions

* fix(process): queue observed output before reactive rendering actions

* test: prune redundant cases and strengthen boundary assertions

* fix(cli): route native value tracing through shared workflows

* test: replace synthetic success with real workflows and captured data

* fix(catalog): separate portable metadata from native host availability
This commit is contained in:
morluto
2026-10-04 16:02:36 +08:00
committed by GitHub
parent 0356f7677f
commit 4fbc501121
205 changed files with 8136 additions and 1816 deletions
+118 -24
View File
@@ -7,9 +7,12 @@ import {
type ProviderIdentity,
type ExecutionOptions,
} from "../application/AnalysisProvider.js";
import { inspectBundleKeyedArchive } from "./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 {
ARTIFACT_ANALYSIS_OPERATIONS,
artifactInventoryInputSchema,
@@ -38,34 +41,47 @@ const IDENTITY: ProviderIdentity = Object.freeze(ARTIFACT_GRAPH_PROVIDER);
/** Read-only inventory and exclusively owned extraction provider. */
export class ArtifactProvider implements AnalysisProvider {
readonly #capabilities: readonly CapabilityDescriptor[];
constructor(
private readonly nativeMountEnabled = false,
private readonly integrityContinueEnabled = false,
) {}
readonly #capabilities: readonly CapabilityDescriptor[] = Object.freeze(
ARTIFACT_ANALYSIS_OPERATIONS.map((operation) =>
Object.freeze({
provider: IDENTITY,
operation,
available: true as const,
reason: null,
effects: Object.freeze({
mutatesArtifact: false,
launchesProcess: operation !== "decode_interface_builder",
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: operation === "extract_artifact",
changesPermissions: false,
requiresRoot: false,
}),
limitations: Object.freeze([
"DMG child inventory is macOS-only and requires per-call approval plus operator policy; PKG remains root-hash-only.",
"ASAR files discovered in filesystem-backed inventories are expanded without bulk extraction; other nested containers remain recorded only.",
]),
platform: NodeJS.Platform = process.platform,
) {
this.#capabilities = Object.freeze(
ARTIFACT_ANALYSIS_OPERATIONS.map((operation) => {
const common = {
provider: IDENTITY,
operation,
effects: Object.freeze({
mutatesArtifact: false,
launchesProcess:
operation !== "decode_interface_builder" &&
operation !== "inspect_keyed_archive",
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: operation === "extract_artifact",
changesPermissions: false,
requiresRoot: false,
}),
limitations: Object.freeze([
"DMG child inventory is macOS-only and requires per-call approval plus operator policy; PKG remains root-hash-only.",
"ASAR files discovered in filesystem-backed inventories are expanded without bulk extraction; other nested containers remain recorded only.",
]),
};
return Object.freeze(
operation === "inspect_asset_catalog" && platform !== "darwin"
? {
...common,
available: false as const,
availabilityCode: "unsupported_host" as const,
reason: "Apple asset catalogs require macOS assetutil.",
}
: { ...common, available: true as const, reason: null },
);
}),
),
);
);
}
identity(): ProviderIdentity {
return IDENTITY;
@@ -138,6 +154,53 @@ class ArtifactClient implements AnalysisClient {
}),
);
}
if (operation === "inspect_keyed_archive") {
const standalone =
this.target.kind === "artifact" && this.target.format === "plist";
if (
standalone &&
parameters.path !== undefined &&
parameters.path !== "." &&
parameters.path !== basename(this.target.path)
)
throw new ArtifactReaderFailure(
"path",
"For an active plist, path must select that archive (omit path or use its basename)",
);
const bundlePath = standalone
? dirname(this.target.path)
: this.target.sourcePath;
if (
bundlePath === undefined ||
(!standalone && !bundlePath.toLowerCase().endsWith(".app"))
)
throw new ArtifactReaderFailure(
"unavailable",
"inspect_keyed_archive requires an active plist or .app bundle",
);
const result = await inspectBundleKeyedArchive({
bundlePath,
targetSha256: this.target.sha256,
parameters: standalone
? { ...parameters, path: basename(this.target.path) }
: parameters,
...(options?.signal === undefined ? {} : { signal: options.signal }),
});
if (standalone && result.archive_sha256 !== this.target.sha256)
throw new ArtifactReaderFailure(
"integrity",
`Active archive digest changed: expected ${this.target.sha256}, observed ${result.archive_sha256}`,
);
return ok(
createAnalysisExecution(result, IDENTITY, {
limitations: result.limitations,
locations: [{ kind: "artifact-path", path: result.archive_path }],
}),
);
}
if (operation === "inspect_asset_catalog") {
return await this.inspectAssetCatalog(parameters, options);
}
if (operation === "extract_artifact") {
const parsed = artifactExtractionExecutionSchema.parse(parameters);
const result = await extractArtifact(
@@ -188,6 +251,37 @@ class ArtifactClient implements AnalysisClient {
return Promise.resolve();
}
private async inspectAssetCatalog(
parameters: Readonly<Record<string, JsonValue>>,
options?: ExecutionOptions,
) {
const bundlePath = this.target.sourcePath;
if (
this.target.kind !== "executable" ||
bundlePath === undefined ||
!bundlePath.toLowerCase().endsWith(".app")
)
throw new ArtifactReaderFailure(
"unavailable",
"inspect_asset_catalog requires an active .app bundle target",
);
const result = await analyzeAppleAssetCatalogs({
bundlePath,
targetSha256: this.target.sha256,
page: parameters,
...(options?.signal === undefined ? {} : { signal: options.signal }),
});
return ok(
createAnalysisExecution(result, IDENTITY, {
limitations: result.limitations,
locations: result.catalogs.map(({ path }) => ({
kind: "artifact-path" as const,
path,
})),
}),
);
}
private async inspectArtifact(
parameters: Readonly<Record<string, JsonValue>>,
options?: ExecutionOptions,
+2
View File
@@ -38,6 +38,8 @@ export class ArtifactReaderFailure extends Error {
| "cancelled"
| "format"
| "integrity"
| "io"
| "limit"
| "path"
| "policy"
| "unavailable",
+81
View File
@@ -0,0 +1,81 @@
import { describe, expect, it } from "vitest";
import { build, buildBinary } from "plist";
import { decodeKeyedArchiveBytes } from "./KeyedArchiveReader.js";
const archive = {
$archiver: "NSKeyedArchiver",
$version: 100000,
$objects: [
"$null",
{
$class: { UID: 4 },
child: { UID: 2 },
shared: { UID: 2 },
self: { UID: 1 },
conditional: { UID: 0 },
broken: { UID: 90 },
},
{ "NS.objects": [{ UID: 1 }, { UID: 3 }] },
"value",
{ $classname: "UnknownModel", $classes: ["UnknownModel", "NSObject"] },
],
$top: { root: { UID: 1 }, other: { UID: 2 } },
};
describe("inert keyed archive decoding", () => {
it("preserves CF$UID, malformed references and original pagination identities", () => {
const bytes = Buffer.from(
build({
...archive,
$objects: [
"$null",
{ bad: { CF$UID: -1 }, valid: { CF$UID: 2 }, broken: { CF$UID: 90 } },
"value",
],
}),
);
const graph = decodeKeyedArchiveBytes(bytes, {
root: "root",
offset: 1,
limit: 1,
});
expect(graph.roots).toEqual({ root: { UID: 1 } });
expect(graph.objects.map(({ id }) => id)).toEqual([1]);
expect(graph.next_offset).toBe(2);
expect(graph.references).toContainEqual(
expect.objectContaining({ source: 1, target: 90, status: "unresolved" }),
);
expect(graph.references).toContainEqual(
expect.objectContaining({ source: 1, target: null, status: "malformed" }),
);
expect(graph.references).toContainEqual(
expect.objectContaining({ source: 1, target: 2, status: "resolved" }),
);
});
it("rejects missing roots, malformed plist, and non-keyed archives", () => {
expect(() =>
decodeKeyedArchiveBytes(Buffer.from("bplist00bad"), {
offset: 0,
limit: 1,
}),
).toThrow();
expect(() =>
decodeKeyedArchiveBytes(Buffer.from(build({ ...archive, $top: {} })), {
offset: 0,
limit: 1,
}),
).toThrow("roots");
expect(() =>
decodeKeyedArchiveBytes(Buffer.from(build({ plain: true })), {
offset: 0,
limit: 1,
}),
).toThrow("NSKeyedArchiver");
expect(() =>
decodeKeyedArchiveBytes(Buffer.from(buildBinary(archive)), {
root: "missing",
offset: 0,
limit: 1,
}),
).toThrow("does not exist");
});
});
+132
View File
@@ -0,0 +1,132 @@
import { createHash } from "node:crypto";
import { parse, parseBinary } from "plist";
import { z } from "zod";
import type { JsonValue } from "../domain/jsonValue.js";
import {
keyedArchiveInputSchema,
keyedArchiveResultSchema,
projectKeyedArchive,
} from "../domain/keyedArchive.js";
import { DirectoryArtifactReader } from "./DirectoryArtifactReader.js";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
const MAX_BYTES = 64 * 1024 * 1024;
/** Parse inert plist bytes, preserving data and dates with explicit typed values. */
export const decodeKeyedArchiveBytes = (
bytes: Buffer,
selection: { root?: string | undefined; offset: number; limit: number },
) => {
if (bytes.length > MAX_BYTES)
throw new RangeError("Keyed archive exceeds 64 MiB");
const binary = bytes.subarray(0, 8).toString("ascii") === "bplist00";
const parsed: unknown = binary
? parseBinary(bytes)
: parse(bytes.toString("utf8"));
return {
archive_format: binary ? ("binary-plist" as const) : ("xml-plist" as const),
...projectKeyedArchive(normalizePlist(parsed), selection),
};
};
const normalizePlist = (value: unknown, depth = 0): JsonValue => {
if (depth > 128) throw new RangeError("Plist exceeds 128 nesting levels");
if (value instanceof Uint8Array)
return {
$plist_type: "data",
base64: Buffer.from(value).toString("base64"),
};
if (value instanceof Date)
return { $plist_type: "date", iso8601: value.toISOString() };
if (Array.isArray(value))
return value.map((item: unknown) => normalizePlist(item, depth + 1));
if (value !== null && typeof value === "object")
return Object.fromEntries(
Object.entries(value).map(([key, item]) => [
key,
normalizePlist(item, depth + 1),
]),
);
return z
.union([z.string(), z.number().finite(), z.boolean(), z.null()])
.parse(value);
};
/** Read exactly one regular, contained bundle entry without following symlinks. */
export const inspectBundleKeyedArchive = async (input: {
bundlePath: string;
targetSha256: string;
parameters: unknown;
signal?: AbortSignal;
}) => {
const selected = keyedArchiveInputSchema.parse(input.parameters);
if (
selected.path.startsWith("/") ||
selected.path
.split("/")
.some((part) => part === ".." || part === "." || part.length === 0)
)
throw new ArtifactReaderFailure(
"path",
"Archive path must be a canonical relative bundle path",
);
const reader = new DirectoryArtifactReader(input.bundlePath);
try {
for await (const entry of reader.entries(input.signal)) {
if (entry.path !== selected.path) continue;
if (entry.kind !== "file")
throw new ArtifactReaderFailure(
"path",
"Archive must be a regular file, not a symlink or directory",
);
if ((entry.declaredSize ?? 0) > MAX_BYTES)
throw new ArtifactReaderFailure(
"limit",
"Keyed archive exceeds 64 MiB",
);
const stream = await reader.open(entry, input.signal);
const chunks: Buffer[] = [];
let size = 0;
for await (const chunk of stream) {
if (input.signal?.aborted) {
stream.destroy();
throw new ArtifactReaderFailure(
"cancelled",
"Archive inspection cancelled",
);
}
const bytes = z.instanceof(Buffer).parse(chunk);
size += bytes.length;
if (size > MAX_BYTES) {
stream.destroy();
throw new ArtifactReaderFailure(
"limit",
"Keyed archive exceeds 64 MiB",
);
}
chunks.push(bytes);
}
const bytes = Buffer.concat(chunks, size);
try {
return keyedArchiveResultSchema.parse({
target_sha256: input.targetSha256,
archive_path: entry.path,
archive_sha256: createHash("sha256").update(bytes).digest("hex"),
...decodeKeyedArchiveBytes(bytes, selected),
});
} catch (cause) {
throw new ArtifactReaderFailure(
cause instanceof RangeError ? "limit" : "format",
"Cannot decode selected Foundation keyed archive",
{ cause },
);
}
}
throw new ArtifactReaderFailure(
"path",
`Archive not found in bundle: ${selected.path}`,
);
} finally {
await reader.close();
}
};