feat(native): add investigation features (#486)

* feat(native): add UI and dispatch investigation workflows

* feat(ghidra): support macOS host validation

* docs: update native investigation capabilities

* feat(artifacts): decode compiled Interface Builder archives

* feat(ghidra): expose bounded p-code value flow

* test(ghidra): split host and cross-format verification

* fix(verify): follow complete result contracts

* refactor: remove unused authorization and schema helpers

* refactor: remove unused evidence result alias

* fix(ghidra): report jump-table evidence precisely

* fix(verify): align browser scenario fixture schema

* fix(setup): compare parsed client config structurally

* test(ghidra): verify AArch64 jump-table mappings

* fix(ghidra): recover AArch64 byte jump tables

* test(artifacts): verify compiled interface builder archives

* feat(native): trace UI actions through handlers

* fix(tests): update native trace and shutdown fixtures

* fix(verification): diagnose browser scenario failures

* fix(browser): wrap scenario snapshots in capture state

* fix(native): bind and bound investigation workflows

* fix(artifacts): preserve bounded interface builder evidence

* fix(ghidra): enforce admitted hosts and preflight tools

* fix(native): preserve trace cancellation and bounds

* test(application): expect bound analysis target evidence

* fix(native): preserve investigation bounds and cancellation

* fix(application): preserve bundle and unresolved trace evidence

* style(test): format artifact subject fixture
This commit is contained in:
morluto
2026-09-30 00:41:05 +08:00
committed by GitHub
parent fa26affc86
commit ed933d1893
87 changed files with 6771 additions and 375 deletions
+30 -1
View File
@@ -9,6 +9,7 @@ import {
} from "../application/AnalysisProvider.js";
import { inventoryArtifact } from "../application/ArtifactInventory.js";
import { extractArtifact } from "../application/ArtifactExtraction.js";
import { analyzeInterfaceBuilderBundle } from "../application/InterfaceBuilderAnalysis.js";
import {
ARTIFACT_ANALYSIS_OPERATIONS,
artifactInventoryInputSchema,
@@ -22,6 +23,7 @@ import {
type AnalysisError,
} from "../domain/errors.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { interfaceBuilderLimitsSchema } from "../domain/interfaceBuilderGraph.js";
import { err, ok } from "../domain/result.js";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
import { ARTIFACT_GRAPH_PROVIDER } from "../application/InvestigationProviders.js";
@@ -50,7 +52,7 @@ export class ArtifactProvider implements AnalysisProvider {
reason: null,
effects: Object.freeze({
mutatesArtifact: false,
launchesProcess: true,
launchesProcess: operation !== "decode_interface_builder",
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: operation === "extract_artifact",
@@ -109,6 +111,33 @@ class ArtifactClient implements AnalysisClient {
const inspected = await this.inspectArtifact(parameters, options);
return inspected;
}
if (operation === "decode_interface_builder") {
if (
this.target.kind !== "executable" ||
this.target.sourcePath === undefined ||
!this.target.sourcePath.toLowerCase().endsWith(".app")
)
throw new ArtifactReaderFailure(
"unavailable",
"decode_interface_builder requires an active .app bundle target",
);
const limits = interfaceBuilderLimitsSchema.parse(parameters);
const result = await analyzeInterfaceBuilderBundle({
bundlePath: this.target.sourcePath,
targetSha256: this.target.sha256,
limits,
...(options?.signal === undefined ? {} : { signal: options.signal }),
});
return ok(
createAnalysisExecution(result, IDENTITY, {
limitations: result.limitations,
locations: result.documents.map(({ relative_path: path }) => ({
kind: "artifact-path" as const,
path,
})),
}),
);
}
if (operation === "extract_artifact") {
const parsed = artifactExtractionExecutionSchema.parse(parameters);
const result = await extractArtifact(
+141
View File
@@ -0,0 +1,141 @@
import { describe, expect, it } from "vitest";
import { decodeNibArchive } from "./NibArchive.js";
const encodeArchive = (input: {
readonly classes: readonly string[];
readonly objects: readonly {
readonly classIndex: number;
readonly values: Readonly<
Record<string, number | string | boolean | null | { ref: number }>
>;
}[];
}): Buffer => {
const keys = [
...new Set(input.objects.flatMap(({ values }) => Object.keys(values))),
];
const keyIndex = new Map(keys.map((key, index) => [key, index]));
const valueRecords = input.objects.flatMap(({ values }) =>
Object.entries(values).map(([key, value]) =>
Buffer.concat([varint(keyIndex.get(key) ?? 0), encodeValue(value)]),
),
);
let valueStart = 0;
const records = input.objects.map(({ classIndex, values }) => {
const count = Object.keys(values).length;
const result = Buffer.concat([
varint(classIndex),
varint(valueStart),
varint(count),
]);
valueStart += count;
return result;
});
const objects = Buffer.concat(records);
const encodedKeys = Buffer.concat(
keys.map((key) =>
Buffer.concat([varint(Buffer.byteLength(key)), Buffer.from(key)]),
),
);
const values = Buffer.concat(valueRecords);
const classes = Buffer.concat(
input.classes.map((name) => {
const bytes = Buffer.from(name);
return Buffer.concat([varint(bytes.length), varint(0), bytes]);
}),
);
const objectsOffset = 50;
const keysOffset = objectsOffset + objects.length;
const valuesOffset = keysOffset + encodedKeys.length;
const classesOffset = valuesOffset + values.length;
const header = Buffer.alloc(50);
header.write("NIBArchive", 0, "ascii");
header.writeUInt32LE(1, 10);
header.writeUInt32LE(10, 14);
header.writeUInt32LE(input.objects.length, 18);
header.writeUInt32LE(objectsOffset, 22);
header.writeUInt32LE(keys.length, 26);
header.writeUInt32LE(keysOffset, 30);
header.writeUInt32LE(valueStart, 34);
header.writeUInt32LE(valuesOffset, 38);
header.writeUInt32LE(input.classes.length, 42);
header.writeUInt32LE(classesOffset, 46);
return Buffer.concat([header, objects, encodedKeys, values, classes]);
};
const varint = (value: number): Buffer => {
const bytes: number[] = [];
let remaining = value;
do {
let byte = remaining & 0x7f;
remaining >>>= 7;
if (remaining === 0) byte |= 0x80;
bytes.push(byte);
} while (remaining > 0);
return Buffer.from(bytes);
};
const encodeValue = (
value: number | string | boolean | null | { ref: number },
): Buffer => {
if (typeof value === "boolean") return Buffer.from([value ? 4 : 5]);
if (value === null) return Buffer.from([9]);
if (typeof value === "number") {
const bytes = Buffer.alloc(5);
bytes[0] = 2;
bytes.writeInt32LE(value, 1);
return bytes;
}
if (typeof value === "object") {
const bytes = Buffer.alloc(5);
bytes[0] = 10;
bytes.writeUInt32LE(value.ref, 1);
return bytes;
}
const data = Buffer.from(value);
return Buffer.concat([Buffer.from([8]), varint(data.length), data]);
};
describe("NIBArchive decoder", () => {
it("decodes bounded object, key, class, and reference tables", () => {
const archive = encodeArchive({
classes: ["NSView\0", "NSString\0"],
objects: [
{ classIndex: 0, values: { child: { ref: 1 }, enabled: true } },
{ classIndex: 1, values: { text: "Button" } },
],
});
const decoded = decodeNibArchive(archive);
expect(decoded.objects).toEqual([
{
id: 0,
class_name: "NSView",
values: { child: { $nib_object_ref: 1 }, enabled: true },
},
{
id: 1,
class_name: "NSString",
values: { text: { $nib_data_base64: "QnV0dG9u" } },
},
]);
expect(decoded.coder_version).toBe(10);
});
it("rejects malformed references and unsupported format versions", () => {
const valid = encodeArchive({
classes: ["NSObject"],
objects: [{ classIndex: 0, values: {} }],
});
const invalidVersion = Buffer.from(valid);
invalidVersion.writeUInt32LE(2, 10);
expect(() => decodeNibArchive(invalidVersion)).toThrow(/Unsupported/u);
const invalidReference = encodeArchive({
classes: ["NSObject"],
objects: [{ classIndex: 0, values: { child: { ref: 4 } } }],
});
expect(() => decodeNibArchive(invalidReference)).toThrow(
/object reference/u,
);
});
});
+428
View File
@@ -0,0 +1,428 @@
import type { JsonValue } from "../domain/jsonValue.js";
import { TextDecoder } from "node:util";
const MAGIC = Buffer.from("NIBArchive", "ascii");
const MAX_RECORDS = 1_000_000;
interface NibObjectRecord {
readonly class_index: number;
readonly value_start: number;
readonly value_count: number;
}
interface NibValueRecord {
readonly key_index: number;
readonly value: JsonValue;
}
/** Parsed NIBArchive payload with the original object indices preserved. */
export interface NibArchiveDocument {
readonly format_version: number;
readonly coder_version: number;
readonly object_count: number;
readonly connection_object_count: number;
readonly objects: readonly {
readonly id: number;
readonly class_name: string;
readonly values: Readonly<Record<string, JsonValue>>;
}[];
readonly classes: readonly string[];
readonly limitations: readonly string[];
}
/** Decode Apple's length-prefixed NIBArchive representation without loading UI classes. */
export const decodeNibArchive = (bytes: Buffer): NibArchiveDocument => {
if (bytes.length < 50 || !bytes.subarray(0, MAGIC.length).equals(MAGIC))
throw new TypeError("NIBArchive magic or header is invalid");
const formatVersion = readU32(bytes, 10);
const coderVersion = readU32(bytes, 14);
if (formatVersion !== 1)
throw new TypeError(
`Unsupported NIBArchive format version ${formatVersion}`,
);
const objectCount = readCount(bytes, 18, "object");
const objectsOffset = readOffset(bytes, 22, bytes.length, "object");
const keyCount = readCount(bytes, 26, "key");
const keysOffset = readOffset(bytes, 30, bytes.length, "key");
const valueCount = readCount(bytes, 34, "value");
const valuesOffset = readOffset(bytes, 38, bytes.length, "value");
const classCount = readCount(bytes, 42, "class");
const classesOffset = readOffset(bytes, 46, bytes.length, "class");
assertOrderedOffsets(bytes.length, [
objectsOffset,
keysOffset,
valuesOffset,
classesOffset,
]);
const objectRecords = parseObjects(
bytes,
objectsOffset,
keysOffset,
objectCount,
valueCount,
classCount,
);
const keys = parseStrings(bytes, keysOffset, valuesOffset, keyCount, "key");
const classes = parseClasses(bytes, classesOffset, bytes.length, classCount);
const neededValues = valueIndexes(objectRecords, valueCount);
const values = parseValues(
bytes,
valuesOffset,
classesOffset,
valueCount,
keyCount,
neededValues,
);
for (const { value } of values.values()) {
if (
typeof value === "object" &&
value !== null &&
!Array.isArray(value) &&
typeof value.$nib_object_ref === "number" &&
value.$nib_object_ref >= objectCount
)
throw new TypeError(
"NIBArchive object reference is outside the object table",
);
}
const objects = objectRecords.flatMap((object, id) => {
const className = classes[object.class_index];
if (className === undefined) return [];
const fields: Record<string, JsonValue> = {};
for (
let index = object.value_start;
index < object.value_start + object.value_count;
index += 1
) {
const value = values.get(index);
if (value === undefined) continue;
const key = keys[value.key_index];
if (key !== undefined) fields[key] = value.value;
}
return [{ id, class_name: className, values: fields }];
});
let connectionObjectCount = 0;
for (const object of objects)
if (
/(?:Outlet|Connection|Segue|ActionConnection)/iu.test(object.class_name)
)
connectionObjectCount += 1;
return {
format_version: formatVersion,
coder_version: coderVersion,
object_count: objectCount,
connection_object_count: connectionObjectCount,
objects,
classes,
limitations: [
"NIBArchive class extensions and unsupported value encodings are retained as unavailable fields.",
"NIBArchive object relationships are decoded from serialized references; runtime object creation and execution are not performed.",
],
};
};
const parseObjects = (
bytes: Buffer,
start: number,
end: number,
count: number,
valueCount: number,
classCount: number,
): NibObjectRecord[] => {
const cursor = { offset: start };
const output: NibObjectRecord[] = [];
for (let index = 0; index < count; index += 1) {
const classIndex = readVarint(bytes, cursor, end);
const valueStart = readVarint(bytes, cursor, end);
const countForObject = readVarint(bytes, cursor, end);
if (
classIndex >= classCount ||
valueStart > valueCount ||
countForObject > valueCount - valueStart
)
throw new TypeError(
`NIBArchive object ${index} references an invalid table range`,
);
output.push({
class_index: classIndex,
value_start: valueStart,
value_count: countForObject,
});
}
if (cursor.offset > end)
throw new TypeError("NIBArchive object table overlaps the next table");
return output;
};
const parseStrings = (
bytes: Buffer,
start: number,
end: number,
count: number,
label: string,
): string[] => {
const cursor = { offset: start };
const output: string[] = [];
for (let index = 0; index < count; index += 1) {
const length = readVarint(bytes, cursor, end);
const next = checkedEnd(cursor.offset, length, end, `${label} ${index}`);
const value = decodeUtf8(bytes, cursor.offset, next, `${label} ${index}`);
cursor.offset = next;
output.push(value);
}
return output;
};
const parseClasses = (
bytes: Buffer,
start: number,
end: number,
count: number,
): string[] => {
const cursor = { offset: start };
const output: string[] = [];
for (let index = 0; index < count; index += 1) {
const length = readVarint(bytes, cursor, end);
const extraCount = readVarint(bytes, cursor, end);
if (extraCount > 16)
throw new TypeError(
`NIBArchive class ${index} has too many extension values`,
);
ensureRange(
cursor.offset,
extraCount * 4,
end,
`class ${index} extensions`,
);
cursor.offset += extraCount * 4;
const next = checkedEnd(cursor.offset, length, end, `class ${index}`);
const name = decodeUtf8(
bytes,
cursor.offset,
next,
`class ${index}`,
).replace(/\0+$/u, "");
cursor.offset = next;
output.push(name);
}
return output;
};
const parseValues = (
bytes: Buffer,
start: number,
end: number,
count: number,
keyCount: number,
needed: ReadonlySet<number>,
): Map<number, NibValueRecord> => {
const cursor = { offset: start };
const output = new Map<number, NibValueRecord>();
for (let index = 0; index < count; index += 1) {
const keyIndex = readVarint(bytes, cursor, end);
if (keyIndex >= keyCount)
throw new TypeError(
`NIBArchive value ${index} references an invalid key`,
);
ensureRange(cursor.offset, 1, end, `value ${index} type`);
const type = bytes[cursor.offset++] ?? -1;
const value = readValue(bytes, cursor, end, type, index);
if (needed.has(index)) output.set(index, { key_index: keyIndex, value });
}
if (cursor.offset > end)
throw new TypeError("NIBArchive value table overlaps the next table");
return output;
};
const readValue = (
bytes: Buffer,
cursor: { offset: number },
end: number,
type: number,
index: number,
): JsonValue => {
switch (type) {
case 0:
ensureRange(cursor.offset, 1, end, `value ${index}`);
return bytes.readInt8(cursor.offset++);
case 1:
ensureRange(cursor.offset, 2, end, `value ${index}`);
{
const value = bytes.readInt16LE(cursor.offset);
cursor.offset += 2;
return value;
}
case 2:
ensureRange(cursor.offset, 4, end, `value ${index}`);
{
const value = bytes.readInt32LE(cursor.offset);
cursor.offset += 4;
return value;
}
case 3:
ensureRange(cursor.offset, 8, end, `value ${index}`);
{
const value = bytes.readBigInt64LE(cursor.offset);
cursor.offset += 8;
return value <= BigInt(Number.MAX_SAFE_INTEGER) &&
value >= BigInt(Number.MIN_SAFE_INTEGER)
? Number(value)
: value.toString();
}
case 4:
return true;
case 5:
return false;
case 6:
ensureRange(cursor.offset, 4, end, `value ${index}`);
{
const value = bytes.readFloatLE(cursor.offset);
cursor.offset += 4;
return Number.isFinite(value) ? value : null;
}
case 7:
ensureRange(cursor.offset, 8, end, `value ${index}`);
{
const value = bytes.readDoubleLE(cursor.offset);
cursor.offset += 8;
return Number.isFinite(value) ? value : null;
}
case 8: {
const length = readVarint(bytes, cursor, end);
const next = checkedEnd(
cursor.offset,
length,
end,
`value ${index} data`,
);
const encoded = bytes.subarray(cursor.offset, next).toString("base64");
cursor.offset = next;
return { $nib_data_base64: encoded };
}
case 9:
return null;
case 10:
ensureRange(cursor.offset, 4, end, `value ${index} reference`);
{
const objectIndex = bytes.readUInt32LE(cursor.offset);
cursor.offset += 4;
return { $nib_object_ref: objectIndex };
}
default:
throw new TypeError(
`NIBArchive value ${index} has unsupported type ${type}`,
);
}
};
const valueIndexes = (
objects: readonly NibObjectRecord[],
total: number,
): ReadonlySet<number> => {
const indexes = new Set<number>();
for (const object of objects)
for (
let index = object.value_start;
index < object.value_start + object.value_count;
index += 1
)
indexes.add(index);
if (indexes.size > total)
throw new TypeError(
"NIBArchive object value ranges exceed the value table",
);
return indexes;
};
const readCount = (bytes: Buffer, offset: number, label: string): number => {
const count = readU32(bytes, offset);
if (count > MAX_RECORDS)
throw new TypeError(`NIBArchive ${label} count exceeds the decoder bound`);
return count;
};
const readOffset = (
bytes: Buffer,
offset: number,
fileLength: number,
label: string,
): number => {
const value = readU32(bytes, offset);
if (value < 50 || value > fileLength)
throw new TypeError(`NIBArchive ${label} table offset is invalid`);
return value;
};
const readU32 = (bytes: Buffer, offset: number): number => {
ensureRange(offset, 4, bytes.length, "header");
return bytes.readUInt32LE(offset);
};
const decodeUtf8 = (
bytes: Buffer,
start: number,
end: number,
label: string,
): string => {
try {
return new TextDecoder("utf-8", { fatal: true }).decode(
bytes.subarray(start, end),
);
} catch {
throw new TypeError(`NIBArchive ${label} is not valid UTF-8`);
}
};
const readVarint = (
bytes: Buffer,
cursor: { offset: number },
end: number,
): number => {
let value = 0;
let shift = 0;
for (let index = 0; index < 5; index += 1) {
ensureRange(cursor.offset, 1, end, "variable integer");
const byte = bytes[cursor.offset++] ?? 0;
value += (byte & 0x7f) * 2 ** shift;
if ((byte & 0x80) !== 0) {
if (value > 0x7fff_ffff)
throw new TypeError("NIBArchive variable integer is out of range");
return value;
}
shift += 7;
}
throw new TypeError("NIBArchive variable integer is too long");
};
const checkedEnd = (
start: number,
length: number,
limit: number,
label: string,
): number => {
if (!Number.isSafeInteger(length) || length < 0 || start + length > limit)
throw new TypeError(`NIBArchive ${label} exceeds its table`);
return start + length;
};
const ensureRange = (
start: number,
length: number,
limit: number,
label: string,
): void => {
checkedEnd(start, length, limit, label);
};
const assertOrderedOffsets = (length: number, offsets: readonly number[]) => {
let previous = 50;
for (const offset of offsets) {
if (offset < previous || offset > length)
throw new TypeError("NIBArchive table offsets are out of order");
previous = offset;
}
};