chore: sync current main into the CI baseline repair
Validate the formatting and reconstruction assertion repairs against the latest merged feature and correctness changes. Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
This commit is contained in:
@@ -417,6 +417,34 @@ describe("Apple bundle layouts and containers", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Apple IPA components", () => {
|
||||
it("excludes AppleDouble sidecars from IPA components", () => {
|
||||
const result = project(
|
||||
inventoryEvidence("ipa", "Fixture.ipa", [
|
||||
{ path: "Payload/Fixture.app/Info.plist" },
|
||||
macho("Payload/Fixture.app/Fixture"),
|
||||
{ path: "Payload/Fixture.app/Contents/Resources/._libfoo.dylib" },
|
||||
{ path: "Payload/Fixture.app/Frameworks/Foo.framework/._Foo" },
|
||||
{ path: "__MACOSX/Payload/Fixture.app/libghost.dylib" },
|
||||
macho("Payload/Fixture.app/Contents/Resources/libreal.dylib"),
|
||||
macho("SwiftSupport/iphoneos/libswiftCore.dylib"),
|
||||
]),
|
||||
);
|
||||
expect(result.components.native_libraries.map(({ path }) => path)).toEqual([
|
||||
"Payload/Fixture.app/Contents/Resources/libreal.dylib",
|
||||
"SwiftSupport/iphoneos/libswiftCore.dylib",
|
||||
]);
|
||||
expect(result.components.frameworks).toEqual([]);
|
||||
expect(result.components.executables.map(({ path }) => path)).toEqual([
|
||||
"Payload/Fixture.app/Contents/Resources/libreal.dylib",
|
||||
"Payload/Fixture.app/Fixture",
|
||||
]);
|
||||
expect(result.limitations).toContainEqual(
|
||||
expect.stringContaining("AppleDouble sidecar entries"),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("macOS application scope", () => {
|
||||
it("attributes only components inside the application roots", () => {
|
||||
const result = project(
|
||||
|
||||
@@ -218,8 +218,9 @@ export const appleProjectionId = (projection: unknown): string =>
|
||||
`aap_${digest(projection)}`;
|
||||
|
||||
/**
|
||||
* IPA projection keeps every archive component, as before. Directory, ZIP,
|
||||
* and DMG inventories can hold installers and other siblings, so only
|
||||
* AppleDouble sidecars describe neighbouring files and are never components.
|
||||
* IPA projection keeps every other archive component, as before. Directory,
|
||||
* ZIP, and DMG inventories can hold installers and other siblings, so only
|
||||
* components inside an application root are attributed to it.
|
||||
*/
|
||||
const attributeComponents = (
|
||||
@@ -227,8 +228,8 @@ const attributeComponents = (
|
||||
roots: readonly string[],
|
||||
rootFormat: RootFormat,
|
||||
): { readonly all: Component[]; readonly unattributed: number } => {
|
||||
if (rootFormat === "ipa") return { all: [...inventoried], unattributed: 0 };
|
||||
const visible = inventoried.filter(({ path }) => !isSidecar(path));
|
||||
if (rootFormat === "ipa") return { all: visible, unattributed: 0 };
|
||||
const all = visible.filter(({ path }) =>
|
||||
roots.some((root) => isWithin(path, root)),
|
||||
);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { addressCoordinate } from "./native/addressCoordinate.js";
|
||||
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
|
||||
@@ -38,16 +39,6 @@ export const addressDistance = (start: string, end: string): number => {
|
||||
);
|
||||
};
|
||||
|
||||
const addressCoordinate = (
|
||||
value: string,
|
||||
): { readonly space: string; readonly offset: bigint } | null => {
|
||||
const separator = value.lastIndexOf(":0x");
|
||||
const space = separator < 0 ? "default" : value.slice(0, separator);
|
||||
const offset = separator < 0 ? value : value.slice(separator + 1);
|
||||
if (!/^0x[0-9a-f]+$/u.test(offset)) return null;
|
||||
return { space, offset: BigInt(offset) };
|
||||
};
|
||||
|
||||
const procedureMapSchema = z.record(z.string(), z.string());
|
||||
const addressedNamesSchema = z.array(
|
||||
z.object({ address: z.string(), name: z.string() }),
|
||||
@@ -128,9 +119,9 @@ export const functionBodySchema = z.discriminatedUnion("available", [
|
||||
})
|
||||
.superRefine((body, context) => {
|
||||
let total = 0n;
|
||||
const bounds = new Map<string, { start: bigint; end: bigint }>();
|
||||
const closedSpaces = new Set<string>();
|
||||
let previousSpace: string | null = null;
|
||||
const bounds = new Map<string | null, { start: bigint; end: bigint }>();
|
||||
const closedSpaces = new Set<string | null>();
|
||||
let previousSpace: string | null | undefined;
|
||||
for (const range of body.ranges) {
|
||||
const start = addressCoordinate(range.start);
|
||||
const end = addressCoordinate(range.end);
|
||||
@@ -146,7 +137,7 @@ export const functionBodySchema = z.discriminatedUnion("available", [
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (previousSpace !== null && previousSpace !== start.space)
|
||||
if (previousSpace !== undefined && previousSpace !== start.space)
|
||||
closedSpaces.add(previousSpace);
|
||||
const previous = bounds.get(start.space);
|
||||
if (
|
||||
|
||||
@@ -339,7 +339,10 @@ const spawnOptions = (candidate: SpawnCandidate): t.ObjectExpression | null => {
|
||||
const spawnArgvCount = (candidate: SpawnCandidate): number | null => {
|
||||
if (candidate.method === "exec") return null;
|
||||
const args = candidate.node.arguments[1];
|
||||
return t.isArrayExpression(args) ? args.elements.length : null;
|
||||
return t.isArrayExpression(args) &&
|
||||
!args.elements.some((element) => t.isSpreadElement(element))
|
||||
? args.elements.length
|
||||
: null;
|
||||
};
|
||||
|
||||
const objectHasProperty = (
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
/** Parse canonical native offsets without discarding their address space. */
|
||||
export const addressCoordinate = (
|
||||
value: string,
|
||||
): { readonly space: string | null; readonly offset: bigint } | null => {
|
||||
const separator = value.lastIndexOf(":0x");
|
||||
if (separator === 0) return null;
|
||||
const space = separator < 0 ? null : value.slice(0, separator);
|
||||
const offset = separator < 0 ? value : value.slice(separator + 1);
|
||||
if (!/^0x[0-9a-f]+$/u.test(offset)) return null;
|
||||
return { space, offset: BigInt(offset) };
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { parseBytePattern } from "./bytePattern.js";
|
||||
|
||||
describe("masked byte patterns", () => {
|
||||
it("preserves whole-byte wildcards and combines explicit bit masks", () => {
|
||||
const parsed = parseBytePattern("48 8b\t??89", "ff f0 ff 0f");
|
||||
if (!parsed.ok) throw parsed.error;
|
||||
expect(parsed.value).toEqual({
|
||||
bytes: [0x48, 0x8b, 0, 0x89],
|
||||
masks: [255, 240, 0, 15],
|
||||
});
|
||||
const exact = parseBytePattern("Aa\u00a000");
|
||||
if (!exact.ok) throw exact.error;
|
||||
expect(exact.value).toEqual({ bytes: [170, 0], masks: [255, 255] });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["", undefined, "pattern"],
|
||||
["4", undefined, "pattern"],
|
||||
["4?", undefined, "pattern"],
|
||||
["gg", undefined, "pattern"],
|
||||
["?? ??", undefined, "pattern"],
|
||||
["ff", "00", "pattern"],
|
||||
["ffff", "ff", "mask"],
|
||||
["ff", "??", "mask"],
|
||||
])("rejects invalid pattern %s with typed issues", (pattern, mask, field) => {
|
||||
const parsed = parseBytePattern(pattern, mask);
|
||||
if (parsed.ok) throw new Error("Expected a rejected pattern");
|
||||
expect(parsed.error.issues).toMatchObject([
|
||||
{ path: [field], reason: "invalid_value" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
import { z } from "zod";
|
||||
import { addressCoordinate } from "./addressCoordinate.js";
|
||||
import { AnalysisInputError } from "../analysisErrorCore.js";
|
||||
import { err, ok, type Result } from "../result.js";
|
||||
|
||||
/** Byte pairs, with whole-byte wildcards; explicit masks can select individual bits. */
|
||||
export const bytePatternFields = {
|
||||
pattern: z
|
||||
.string()
|
||||
.regex(/^([0-9a-fA-F]{2}|\?\?)(\s*([0-9a-fA-F]{2}|\?\?))*$/u),
|
||||
mask: z
|
||||
.string()
|
||||
.regex(/^[0-9a-fA-F]{2}(\s*[0-9a-fA-F]{2})*$/u)
|
||||
.optional(),
|
||||
};
|
||||
|
||||
/** Parse once at the input boundary, retaining typed correction issues. */
|
||||
export const parseBytePattern = (
|
||||
pattern: string,
|
||||
mask?: string,
|
||||
): Result<{ bytes: number[]; masks: number[] }, AnalysisInputError> => {
|
||||
const invalid = (field: string, message: string) =>
|
||||
err(
|
||||
new AnalysisInputError("search_bytes", undefined, [
|
||||
{ path: [field], reason: "invalid_value", message },
|
||||
]),
|
||||
);
|
||||
if (!bytePatternFields.pattern.safeParse(pattern).success)
|
||||
return invalid("pattern", "Use hexadecimal byte pairs or ?? wildcards");
|
||||
if (mask !== undefined && !bytePatternFields.mask.safeParse(mask).success)
|
||||
return invalid("mask", "Use hexadecimal mask byte pairs");
|
||||
const pairs = pattern.replace(/\s/gu, "").match(/../gu) ?? [];
|
||||
const maskPairs = mask?.replace(/\s/gu, "").match(/../gu);
|
||||
if (maskPairs && maskPairs.length !== pairs.length)
|
||||
return invalid("mask", "Mask length must equal pattern length");
|
||||
const bytes = pairs.map((pair) =>
|
||||
pair === "??" ? 0 : Number.parseInt(pair, 16),
|
||||
);
|
||||
const masks = pairs.map((pair, index) =>
|
||||
pair === "??" ? 0 : Number.parseInt(maskPairs?.[index] ?? "ff", 16),
|
||||
);
|
||||
if (!masks.some((value) => value !== 0))
|
||||
return invalid("pattern", "Pattern must constrain at least one bit");
|
||||
return ok({ bytes, masks });
|
||||
};
|
||||
|
||||
/** Shared semantic validation for public and provider inputs. */
|
||||
export const validateBytePattern = (
|
||||
value: { pattern: string; mask?: string | undefined },
|
||||
context: z.RefinementCtx,
|
||||
): void => {
|
||||
const parsed = parseBytePattern(value.pattern, value.mask);
|
||||
if (!parsed.ok)
|
||||
for (const issue of parsed.error.issues)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: [...issue.path],
|
||||
message: issue.message ?? "Invalid byte pattern",
|
||||
});
|
||||
};
|
||||
|
||||
const coverageBlock = z
|
||||
.strictObject({
|
||||
segment: z.string(),
|
||||
start: z.string(),
|
||||
end: z.string(),
|
||||
bytes: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
||||
})
|
||||
.superRefine((value, context) => {
|
||||
const start = addressCoordinate(value.start);
|
||||
const end = addressCoordinate(value.end);
|
||||
if (
|
||||
start === null ||
|
||||
end === null ||
|
||||
start.space !== end.space ||
|
||||
start.offset > end.offset ||
|
||||
end.offset - start.offset + 1n !== BigInt(value.bytes)
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message:
|
||||
"Byte coverage must equal its inclusive address range in one space",
|
||||
});
|
||||
});
|
||||
|
||||
/** Inclusive page coverage; matches never span memory blocks. */
|
||||
export const byteSearchResultSchema = z
|
||||
.strictObject({
|
||||
matches: z
|
||||
.array(
|
||||
z.strictObject({
|
||||
address: z.string(),
|
||||
segment: z.string(),
|
||||
file_offset: z
|
||||
.number()
|
||||
.int()
|
||||
.nonnegative()
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.nullable(),
|
||||
procedure: z
|
||||
.strictObject({ address: z.string(), name: z.string() })
|
||||
.nullable(),
|
||||
}),
|
||||
)
|
||||
.max(1000),
|
||||
searched: z.strictObject({
|
||||
blocks: z.array(coverageBlock),
|
||||
bytes: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
||||
skipped_uninitialized: z.array(coverageBlock),
|
||||
skipped_not_loaded: z.array(coverageBlock),
|
||||
}),
|
||||
complete: z.boolean(),
|
||||
next_cursor: z.string().min(1).nullable(),
|
||||
})
|
||||
.superRefine((value, context) => {
|
||||
if (
|
||||
value.complete !== (value.next_cursor === null) ||
|
||||
value.searched.bytes !==
|
||||
value.searched.blocks.reduce((sum, block) => sum + block.bytes, 0)
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Byte search coverage and continuation disagree",
|
||||
});
|
||||
});
|
||||
@@ -53,6 +53,7 @@ const source = (
|
||||
digit: string,
|
||||
observation: Partial<EvidenceObservation> = {},
|
||||
hasSubject = true,
|
||||
hasCoverage = true,
|
||||
): Evidence =>
|
||||
createEvidence(
|
||||
hasSubject
|
||||
@@ -69,7 +70,9 @@ const source = (
|
||||
result: dossier,
|
||||
confidence: "derived",
|
||||
authority: "shipped-artifact",
|
||||
relationshipCoverage: { status: "complete" },
|
||||
...(hasCoverage
|
||||
? { relationshipCoverage: { status: "complete" as const } }
|
||||
: {}),
|
||||
...observation,
|
||||
},
|
||||
);
|
||||
@@ -197,6 +200,118 @@ describe("function reconstruction source parameters", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("historical calls-only reconstruction changes", () => {
|
||||
it.each(["missing", "unknown", "partial", "unresolved"] as const)(
|
||||
"keeps historical calls-only changes unknown with %s call coverage",
|
||||
(coverage) => {
|
||||
const changedDossier = functionDossierSchema.parse({
|
||||
...functionDossierSchema.parse(dossier),
|
||||
callees: [
|
||||
{
|
||||
address: "0x2000",
|
||||
name: "puts",
|
||||
classification: null,
|
||||
body: { available: false, reason: "External function." },
|
||||
},
|
||||
],
|
||||
});
|
||||
const complete = source("8", {
|
||||
result: jsonValueSchema.parse(changedDossier),
|
||||
});
|
||||
const incomplete = source(
|
||||
"9",
|
||||
{
|
||||
result: jsonValueSchema.parse({
|
||||
...changedDossier,
|
||||
...(coverage === "unresolved"
|
||||
? {
|
||||
unresolved_calls: [
|
||||
{
|
||||
address: "0x1004",
|
||||
reason: "Computed target unresolved.",
|
||||
},
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
}),
|
||||
...(coverage === "missing"
|
||||
? {}
|
||||
: {
|
||||
relationshipCoverage:
|
||||
coverage === "unknown"
|
||||
? { status: "unknown", reason: "Call graph unavailable." }
|
||||
: coverage === "partial"
|
||||
? {
|
||||
status: "partial",
|
||||
limitations: ["Additional edges omitted."],
|
||||
}
|
||||
: { status: "complete" },
|
||||
}),
|
||||
},
|
||||
true,
|
||||
coverage !== "missing",
|
||||
);
|
||||
const historicalResult = compareFunctions(left, complete);
|
||||
expect(historicalResult).toMatchObject({
|
||||
status: "changed",
|
||||
summary: { changed: 1 },
|
||||
});
|
||||
expect(historicalResult.changes).toMatchObject([
|
||||
{ dimension: "calls", status: "changed" },
|
||||
]);
|
||||
const completeComparison = comparison(
|
||||
{
|
||||
left_evidence_id: left.evidence_id,
|
||||
right_evidence_id: complete.evidence_id,
|
||||
},
|
||||
{},
|
||||
[left, complete],
|
||||
{},
|
||||
historicalResult,
|
||||
);
|
||||
expect(
|
||||
admittedVerification(completeComparison, [left, complete], "overall")()
|
||||
.status,
|
||||
).toBe("fail");
|
||||
const evidence = comparison(
|
||||
{
|
||||
left_evidence_id: left.evidence_id,
|
||||
right_evidence_id: incomplete.evidence_id,
|
||||
},
|
||||
{},
|
||||
[left, incomplete],
|
||||
{},
|
||||
historicalResult,
|
||||
);
|
||||
const before = JSON.stringify(evidence);
|
||||
for (const dimension of ["calls", "overall"] as const) {
|
||||
expect(
|
||||
admittedVerification(evidence, [left, incomplete], dimension)(),
|
||||
).toMatchObject({
|
||||
status: "unknown",
|
||||
summary: { total: 1, passed: 0, failed: 0, unknown: 1 },
|
||||
claims: {
|
||||
items: [
|
||||
expect.objectContaining({
|
||||
status: "unknown",
|
||||
observed_status: "changed",
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining(`Source ${incomplete.evidence_id}:`),
|
||||
]),
|
||||
}),
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
expect(
|
||||
admittedVerification(evidence, [left, incomplete], "pseudocode")()
|
||||
.status,
|
||||
).toBe("pass");
|
||||
expect(JSON.stringify(evidence)).toBe(before);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("function reconstruction call coverage", () => {
|
||||
it("rechecks old unchanged comparisons without affecting unrelated finite dimensions", () => {
|
||||
const incomplete = source("7", {
|
||||
|
||||
@@ -144,10 +144,15 @@ const evaluateClaim = (
|
||||
return source;
|
||||
});
|
||||
const functionSourceFacts = readValidatedSourceFacts(claim, sources);
|
||||
const observed = observedStatus(claim, comparison);
|
||||
const observation = comparisonObservation(claim, comparison);
|
||||
const observed = observation.status;
|
||||
const limitations = [
|
||||
...authorityLimitations(claim, sources, sides),
|
||||
...sourceCallCoverageLimitations(claim, functionSourceFacts, observed),
|
||||
...sourceCallCoverageLimitations(
|
||||
claim,
|
||||
functionSourceFacts,
|
||||
observation.hasIndependentFunctionChange === true,
|
||||
),
|
||||
];
|
||||
const relatedUnknowns = reconstructionClaimUnknowns(
|
||||
heads,
|
||||
@@ -235,21 +240,40 @@ const validateComparisonIdentity = (claim: Claim, evidence: Evidence): void => {
|
||||
throw new TypeError("Comparison Evidence identity or authority disagrees");
|
||||
};
|
||||
|
||||
const observedStatus = (claim: Claim, evidence: Evidence): ObservedStatus => {
|
||||
const comparisonObservation = (
|
||||
claim: Claim,
|
||||
evidence: Evidence,
|
||||
): {
|
||||
readonly status: ObservedStatus;
|
||||
readonly hasIndependentFunctionChange?: boolean;
|
||||
} => {
|
||||
if (claim.kind === "behavioral") {
|
||||
const result = processCaptureComparisonSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
validateProcessStatus(result);
|
||||
return claim.dimension === "overall"
|
||||
? result.status
|
||||
: result[claim.dimension];
|
||||
return {
|
||||
status:
|
||||
claim.dimension === "overall" ? result.status : result[claim.dimension],
|
||||
};
|
||||
}
|
||||
if (claim.kind === "structural-function") {
|
||||
const result = functionComparisonResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
if (claim.dimension === "overall") return result.status;
|
||||
if (claim.dimension === "overall")
|
||||
return {
|
||||
status: result.status,
|
||||
// Historical overall changes may come solely from incomplete call sets.
|
||||
hasIndependentFunctionChange:
|
||||
result.function_match.status === "mismatched" ||
|
||||
(result.function_match.status === "matched" &&
|
||||
result.dimensions.some(
|
||||
(dimension) =>
|
||||
dimension.dimension !== "calls" &&
|
||||
dimension.status === "changed",
|
||||
)),
|
||||
};
|
||||
const dimension = result.dimensions.find(
|
||||
(item) => item.dimension === claim.dimension,
|
||||
);
|
||||
@@ -263,7 +287,7 @@ const observedStatus = (claim: Claim, evidence: Evidence): ObservedStatus => {
|
||||
throw new TypeError(
|
||||
"Function dimension cites Evidence outside comparison closure",
|
||||
);
|
||||
return dimension.status;
|
||||
return { status: dimension.status };
|
||||
}
|
||||
const result = artifactComparisonResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
@@ -276,7 +300,7 @@ const observedStatus = (claim: Claim, evidence: Evidence): ObservedStatus => {
|
||||
throw new TypeError(
|
||||
"Artifact change cites Evidence outside comparison closure",
|
||||
);
|
||||
return result.status;
|
||||
return { status: result.status };
|
||||
};
|
||||
|
||||
const validateProcessStatus = (
|
||||
@@ -340,12 +364,12 @@ const authorityLimitations = (
|
||||
const sourceCallCoverageLimitations = (
|
||||
claim: Claim,
|
||||
functionSources: readonly FunctionSourceFacts[],
|
||||
observed: ObservedStatus,
|
||||
hasIndependentFunctionChange: boolean,
|
||||
): string[] => {
|
||||
if (
|
||||
claim.kind !== "structural-function" ||
|
||||
(claim.dimension !== "calls" &&
|
||||
!(claim.dimension === "overall" && observed !== "changed"))
|
||||
!(claim.dimension === "overall" && !hasIndependentFunctionChange))
|
||||
)
|
||||
return [];
|
||||
return functionSources.flatMap(({ evidence_id, callCoverageLimitations }) =>
|
||||
|
||||
@@ -8,6 +8,48 @@ import { createWebTextArtifact } from "./webContentArtifact.js";
|
||||
|
||||
const origin = "https://app.example.test";
|
||||
|
||||
it.each([
|
||||
{
|
||||
kind: "recovered",
|
||||
source: "function legacy(a, a) { return a; } fetch('/partial');",
|
||||
parsed: 2,
|
||||
failures: 0,
|
||||
reason: "recovered",
|
||||
endpoints: ["/partial", "/complete"],
|
||||
},
|
||||
{
|
||||
kind: "failed",
|
||||
source: "function broken( {",
|
||||
parsed: 1,
|
||||
failures: 1,
|
||||
reason: "could not be parsed",
|
||||
endpoints: ["/complete"],
|
||||
},
|
||||
])(
|
||||
"attributes $kind parse uncertainty only to its affected source",
|
||||
({ source, parsed, failures, reason, endpoints }) => {
|
||||
const captured = inspection(source);
|
||||
const good = inspection("fetch('/complete');").scripts.items[0];
|
||||
if (good === undefined) throw new Error("Missing valid script fixture");
|
||||
captured.scripts.items.push({ ...good, script_key: "valid-script" });
|
||||
captured.scripts.total += 1;
|
||||
const result = analyzeCapturedWebBundle(captured);
|
||||
expect(result.completeness).toMatchObject({
|
||||
status: "partial",
|
||||
parsed_scripts: parsed,
|
||||
parse_failures: failures,
|
||||
});
|
||||
expect(result.unknowns).toContainEqual({
|
||||
dimension: "javascript_ast",
|
||||
reason: expect.stringContaining(reason),
|
||||
affected_script_keys: [captured.scripts.items[0]?.script_key],
|
||||
});
|
||||
expect(result.observations.endpoints.map(({ value }) => value)).toEqual(
|
||||
endpoints,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
describe("web bundle analyzer", () => {
|
||||
it("extracts graph, route, endpoint, vendor, and WebMCP evidence", () => {
|
||||
const source = `
|
||||
@@ -714,3 +756,54 @@ it("keeps RPC lexical identity and bundled factory recognition in captured scrip
|
||||
]);
|
||||
expect(result.completeness.status).toBe("complete");
|
||||
});
|
||||
|
||||
it("retains distinct WebMCP descriptions and names while deduplicating equivalent properties", () => {
|
||||
const result = analyzeCapturedWebBundle(
|
||||
inspection(`
|
||||
document.modelContext.registerTool({ name: "lookup", description: "first", inputSchema: { properties: { alpha: {} } } });
|
||||
document.modelContext.registerTool({ name: "lookup", description: "second", inputSchema: { properties: { alpha: {} } } });
|
||||
document.modelContext.registerTool({ name: "equivalent", inputSchema: { properties: { alpha: {}, beta: {} } } });
|
||||
document.modelContext.registerTool({ name: "equivalent", inputSchema: { properties: { beta: {}, alpha: {}, alpha: {} } } });
|
||||
document.modelContext.registerTool({ description: "unnamed" });
|
||||
document.modelContext.registerTool({ name: "", description: "unnamed" });
|
||||
`),
|
||||
);
|
||||
|
||||
expect(
|
||||
result.observations.webmcp_declarations.map(
|
||||
({ name, description, schema_property_names }) => ({
|
||||
name,
|
||||
description,
|
||||
schema_property_names,
|
||||
}),
|
||||
),
|
||||
).toEqual([
|
||||
{
|
||||
name: "lookup",
|
||||
description: "first",
|
||||
schema_property_names: ["alpha"],
|
||||
},
|
||||
{
|
||||
name: "lookup",
|
||||
description: "second",
|
||||
schema_property_names: ["alpha"],
|
||||
},
|
||||
{
|
||||
name: "equivalent",
|
||||
description: null,
|
||||
schema_property_names: ["alpha", "beta"],
|
||||
},
|
||||
{ name: null, description: "unnamed", schema_property_names: [] },
|
||||
{ name: "", description: "unnamed", schema_property_names: [] },
|
||||
]);
|
||||
expect(result.observations.webmcp_declarations[2]?.location).toEqual({
|
||||
script_key: `scr_${"1".repeat(64)}`,
|
||||
line: 4,
|
||||
column: 6,
|
||||
});
|
||||
expect(
|
||||
result.observations.webmcp_declarations.every(
|
||||
({ trust }) => trust === "page-declared-untrusted",
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
@@ -50,7 +50,8 @@ export interface AnalysisAccumulator {
|
||||
readonly seen: Set<string>;
|
||||
visitedNodes: number;
|
||||
parsedScripts: number;
|
||||
parseFailures: number;
|
||||
readonly failedScripts: string[];
|
||||
readonly recoveredScripts: string[];
|
||||
}
|
||||
|
||||
export const analyzeScript = (
|
||||
@@ -67,10 +68,12 @@ export const analyzeScript = (
|
||||
} catch (cause: unknown) {
|
||||
// Unparseable scripts are counted; the failure needs no extra detail.
|
||||
void cause;
|
||||
accumulator.parseFailures += 1;
|
||||
accumulator.failedScripts.push(script.script_key);
|
||||
return;
|
||||
}
|
||||
accumulator.parsedScripts += 1;
|
||||
if ((file.errors?.length ?? 0) > 0)
|
||||
accumulator.recoveredScripts.push(script.script_key);
|
||||
detectVendorFingerprints(script, accumulator);
|
||||
const openReceiverFacts = classifyParsedJavaScriptOpenReceivers(file);
|
||||
const rpc = createJavaScriptRpcScan(
|
||||
@@ -293,19 +296,18 @@ const addWebMcpDeclaration = (
|
||||
: [],
|
||||
)
|
||||
: [];
|
||||
const metadata = {
|
||||
name: name ?? null,
|
||||
description: description ?? null,
|
||||
schema_property_names: [...new Set(schemaPropertyNames)].sort(),
|
||||
};
|
||||
// Deduplicate the metadata we return, preserving omission and descriptions.
|
||||
// Property names are a variable-length source-derived list: NUL-joins
|
||||
// would collapse ["a\0b"] with ["a", "b"] and drop a declaration.
|
||||
const key = compositeKey([
|
||||
"webmcp",
|
||||
script.script_key,
|
||||
name ?? "",
|
||||
schemaPropertyNames,
|
||||
]);
|
||||
const key = compositeKey(["webmcp", script.script_key, metadata]);
|
||||
addUnique(accumulator, key, () =>
|
||||
accumulator.webMcp.push({
|
||||
name: name ?? null,
|
||||
description: description ?? null,
|
||||
schema_property_names: [...new Set(schemaPropertyNames)].sort(),
|
||||
...metadata,
|
||||
trust: "page-declared-untrusted",
|
||||
location: location(script.script_key, node),
|
||||
}),
|
||||
@@ -387,7 +389,8 @@ export const emptyAccumulator = (): AnalysisAccumulator => ({
|
||||
seen: new Set(),
|
||||
visitedNodes: 0,
|
||||
parsedScripts: 0,
|
||||
parseFailures: 0,
|
||||
failedScripts: [],
|
||||
recoveredScripts: [],
|
||||
});
|
||||
|
||||
export const isIncludedScript = (
|
||||
|
||||
@@ -25,7 +25,8 @@ export const buildWebBundleAnalysis = (
|
||||
const sourceMapIncomplete =
|
||||
sourceMaps.status === "partial" || sourceMaps.status === "unavailable";
|
||||
const partial =
|
||||
accumulator.parseFailures > 0 ||
|
||||
accumulator.failedScripts.length > 0 ||
|
||||
accumulator.recoveredScripts.length > 0 ||
|
||||
unavailable.length > 0 ||
|
||||
sourceMapIncomplete ||
|
||||
omittedScripts !== undefined ||
|
||||
@@ -44,9 +45,9 @@ export const buildWebBundleAnalysis = (
|
||||
},
|
||||
inferences: accumulator.inferences,
|
||||
unknowns: buildUnknowns({
|
||||
sourceScripts,
|
||||
unavailable,
|
||||
parseFailures: accumulator.parseFailures,
|
||||
failedScripts: accumulator.failedScripts,
|
||||
recoveredScripts: accumulator.recoveredScripts,
|
||||
sourceMaps,
|
||||
omittedScripts,
|
||||
omittedSourceMaps,
|
||||
@@ -54,7 +55,7 @@ export const buildWebBundleAnalysis = (
|
||||
completeness: buildCompleteness({
|
||||
partial,
|
||||
parsedScripts: accumulator.parsedScripts,
|
||||
parseFailures: accumulator.parseFailures,
|
||||
parseFailures: accumulator.failedScripts.length,
|
||||
visitedNodes: accumulator.visitedNodes,
|
||||
}),
|
||||
limitations: bundleLimitations(),
|
||||
@@ -88,9 +89,9 @@ const chunkNode = (script: IncludedScript) => {
|
||||
};
|
||||
|
||||
interface UnknownsInput {
|
||||
readonly sourceScripts: IncludedScript[];
|
||||
readonly unavailable: string[];
|
||||
readonly parseFailures: number;
|
||||
readonly failedScripts: readonly string[];
|
||||
readonly recoveredScripts: readonly string[];
|
||||
readonly sourceMaps: WebBundleAnalysis["observations"]["source_maps"];
|
||||
readonly omittedScripts: number | null | undefined;
|
||||
readonly omittedSourceMaps: number | null | undefined;
|
||||
@@ -115,15 +116,23 @@ const buildUnknowns = (input: UnknownsInput): WebBundleAnalysis["unknowns"] => [
|
||||
affected_script_keys: input.unavailable,
|
||||
},
|
||||
]),
|
||||
...(input.parseFailures === 0
|
||||
...(input.failedScripts.length === 0
|
||||
? []
|
||||
: [
|
||||
{
|
||||
dimension: "javascript_ast" as const,
|
||||
reason: "One or more source artifacts could not be parsed",
|
||||
affected_script_keys: input.sourceScripts.map(
|
||||
({ script_key }) => script_key,
|
||||
),
|
||||
affected_script_keys: [...input.failedScripts],
|
||||
},
|
||||
]),
|
||||
...(input.recoveredScripts.length === 0
|
||||
? []
|
||||
: [
|
||||
{
|
||||
dimension: "javascript_ast" as const,
|
||||
reason:
|
||||
"The parser recovered from errors in one or more source artifacts; findings may be incomplete",
|
||||
affected_script_keys: [...input.recoveredScripts],
|
||||
},
|
||||
]),
|
||||
...(input.omittedSourceMaps === undefined
|
||||
|
||||
Reference in New Issue
Block a user