feat(harmony): project HarmonyOS package inventory evidence (#1447)

* feat(harmony): project HarmonyOS package inventory evidence

First HarmonyOS increment from #1431: HAP, HSP, and App Pack roots are
classified through the hardened ZIP reader and projected into an
execution-free application graph with packaging-model hints, exact
component paths and hashes, App Pack children by path, runtime-family
hints, and path-based N-API bridge hypotheses. HarmonyOS .har stays
unclassified by suffix because .har also names HTTP Archive JSON.

Adds the project_harmony_application_graph tool (CLI and MCP), synthetic
composition coverage, a pinned real-package verify lane, and docs.

* refactor(domain): share application graph projection scaffolding

The HarmonyOS projection mirrors the Android and Apple projections by
design, which pushed jscpd duplication over its 2.5 percent budget.
Extract the identical pieces (inventory input schema, projected
component schema and occurrence flattening, bridge candidate schema
factory, coverage assembly, comparator, canonical digest) into
domain/mobileApplicationGraphProjection.ts and route all three
projections plus the composition fixtures through it. Duplication drops
from 2.52 to 2.49 percent with no behavior change: projection ids,
classifications, and limitations are byte-identical.

* fix(harmony): address review, stable app-pack roots, and rotated fixture

- rebased onto main; the shared projection scaffolding now keeps main's
  nativeRuntimeConvention loop and the harmony runtime families adopt the
  same react-native/flutter/unity path conventions
- the .app App Pack suffix is now a root-input rule only (verified ZIP
  magic in classifyRootFormat and BinaryTargetResolver); nested .app ZIP
  members inside other packages keep the generic zip classification, with
  a regression test, so existing inventories do not change
- the signing limitation now states that an empty signing list does not
  mean unsigned because packaging-tool signatures live in the ZIP signing
  block, and the app-pack root rule is disclosed as suffix-based
- repinned the real-package fixture to the current VHome 2.6.14-beta asset
  after the upstream deleted v5.0.111-beta and replaced the v2.6.14-beta
  asset within hours; the pin records both observed digests

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
BaaRai
2026-10-11 20:09:21 +08:00
committed by GitHub
co-authored by morluto
parent b2da21abe1
commit f2150eb9a7
30 changed files with 1290 additions and 111 deletions
+5 -1
View File
@@ -29,6 +29,7 @@ import {
import { mzWindowsHeaderOffset } from "../domain/dosMz.js";
import {
hasZipSignature,
isZipPackageFormat,
zipPackageFormatForPath,
} from "../domain/zipPackageFormat.js";
@@ -203,6 +204,9 @@ const detectArtifactFormat = async (
const observed = await handle.read(magic, 0, magic.length, 0);
throwIfTargetResolutionCancelled(signal);
if (hasZipSignature(magic.subarray(0, observed.bytesRead))) {
// The HarmonyOS App Pack suffix `.app` is a root-input concept; a nested
// ZIP member ending in `.app` keeps the generic zip classification.
if (lower.endsWith(".app")) return "app-pack";
return zipPackageFormatForPath(lower) ?? "zip";
}
const named = namedArtifactFormat(lower);
@@ -243,7 +247,7 @@ const isArchiveFormat = (
"analysis-database" | "mach-o" | "elf" | "pe" | "dos-mz" | "dos-com"
>,
): format is Extract<BinaryTarget, { kind: "archive" }>["format"] =>
["zip", "ipa", "apk", "msix", "appx", "asar", "dmg", "pkg"].includes(format);
isZipPackageFormat(format) || ["asar", "dmg", "pkg"].includes(format);
const sha256Handle = async (
handle: FileHandle,
@@ -65,6 +65,13 @@ export const ANDROID_APPLICATION_PROVIDER = {
version: "1",
} as const;
/** Provider identity for deterministic HarmonyOS application projections. */
export const HARMONY_APPLICATION_PROVIDER = {
id: "rea-harmony-application",
name: "REA HarmonyOS application workflows",
version: "1",
} as const;
/** Provider identity for verified publication of retained website scripts. */
export const WEB_SCRIPT_EXPORT_PROVIDER = {
id: "rea-web-script-export",
@@ -0,0 +1,28 @@
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { Evidence } from "../../domain/evidence.js";
import {
harmonyApplicationProjectionInputSchema,
projectHarmonyApplication,
} from "../../domain/harmony/harmonyApplication.js";
import type { Result } from "../../domain/result.js";
import { HARMONY_APPLICATION_PROVIDER } from "../InvestigationProviders.js";
import { projectInventoryEvidence } from "../InventoryProjectionEvidence.js";
const OPERATION = "project_harmony_application_graph" as const;
/** Project authenticated HarmonyOS package inventory Evidence into application evidence. */
export const projectHarmonyApplicationEvidence = (
rawInput: unknown,
): Result<Evidence, AnalysisError> => {
return projectInventoryEvidence({
rawInput,
schema: harmonyApplicationProjectionInputSchema,
project: projectHarmonyApplication,
operation: OPERATION,
predicateType: "rea.harmony-application-graph",
provider: HARMONY_APPLICATION_PROVIDER,
subjectFormat: (first) => first.subject?.format ?? "unknown",
protocolError:
"HarmonyOS application projection produced an invalid result",
});
};
@@ -14,6 +14,7 @@ import type {
} from "../../domain/artifactGraph.js";
import {
hasZipSignature,
isZipPackageFormat,
zipPackageFormatForPath,
type ZipPackageFormat,
} from "../../domain/zipPackageFormat.js";
@@ -217,9 +218,8 @@ export const rootOccurrenceFor = (
entry_kind: metadata.format === "directory" ? "directory" : "file",
artifact_kind:
metadata.format === "directory" ||
["zip", "ipa", "apk", "msix", "appx", "asar", "dmg", "pkg"].includes(
metadata.format,
)
isZipPackageFormat(metadata.format) ||
["asar", "dmg", "pkg"].includes(metadata.format)
? "container"
: artifactRoleForFormat(metadata.path, metadata.format).kind,
artifact_format: metadata.format,
+11 -9
View File
@@ -9,7 +9,9 @@ import { ARTIFACT_CLASSIFICATION_PREFIX_BYTES } from "../ArtifactHash.js";
import type { ArtifactOccurrence } from "../../domain/artifactGraph.js";
import {
hasZipSignature,
isZipPackageFormat,
zipPackageFormatForPath,
type ZipPackageFormat,
} from "../../domain/zipPackageFormat.js";
import { ArtifactReaderFailure } from "../ArtifactReader.js";
import type { ArtifactResourceOwner } from "../ArtifactResourceScope.js";
@@ -109,7 +111,8 @@ export const classifyAndHashRootForInventory = async (
initial,
options.signal,
);
const retainSource = isZipFormat(format) || format === "mach-o-universal";
const retainSource =
isZipPackageFormat(format) || format === "mach-o-universal";
outcome = {
kind: "completed",
value: {
@@ -138,13 +141,6 @@ export const classifyAndHashRootForInventory = async (
return outcome.value;
};
const isZipFormat = (format: ArtifactOccurrence["artifact_format"]): boolean =>
format === "zip" ||
format === "ipa" ||
format === "apk" ||
format === "msix" ||
format === "appx";
const classifyRootFormat = async (
path: string,
handle: FileHandle,
@@ -153,7 +149,7 @@ const classifyRootFormat = async (
const observed = await handle.read(magic, 0, magic.length, 0);
const prefix = magic.subarray(0, observed.bytesRead);
const lower = path.toLowerCase();
if (hasZipSignature(prefix)) return zipPackageFormatForPath(lower) ?? "zip";
if (hasZipSignature(prefix)) return zipRootPackageFormat(lower);
if (
lower.endsWith(".pkg") &&
prefix.subarray(0, 4).toString("ascii") === "xar!"
@@ -165,6 +161,12 @@ const classifyRootFormat = async (
.format;
};
/** App Pack is a verified ZIP root role; nested .app members retain their observed format. */
const zipRootPackageFormat = (lower: string): ZipPackageFormat =>
lower.endsWith(".app")
? "app-pack"
: (zipPackageFormatForPath(lower) ?? "zip");
const hasKolyTrailer = async (handle: FileHandle): Promise<boolean> => {
const size = (await handle.stat()).size;
if (size < 512) return false;
+7 -12
View File
@@ -5,7 +5,10 @@ import { MachOSliceArtifactReader } from "../MachOSliceArtifactReader.js";
import { NativeDmgArtifactReader } from "../NativeDmgArtifactReader.js";
import { ZipArtifactReader } from "../ZipArtifactReader.js";
import type { ArtifactOccurrence } from "../../domain/artifactGraph.js";
import { ZIP_NON_ENTRY_TAIL_LIMITATION } from "../../domain/zipPackageFormat.js";
import {
isZipPackageFormat,
ZIP_NON_ENTRY_TAIL_LIMITATION,
} from "../../domain/zipPackageFormat.js";
import type { StableRegularFileDescriptor } from "../../filesystem/RegularFile.js";
export const createReader = (
@@ -14,15 +17,11 @@ export const createReader = (
environment: Readonly<NodeJS.ProcessEnv>,
rootSource?: StableRegularFileDescriptor,
): ArtifactReader | undefined => {
if (isZipPackageFormat(format))
return new ZipArtifactReader(path, format, undefined, rootSource);
switch (format) {
case "directory":
return new DirectoryArtifactReader(path);
case "zip":
case "ipa":
case "apk":
case "msix":
case "appx":
return new ZipArtifactReader(path, format, undefined, rootSource);
case "asar":
return new AsarArtifactReader(path);
case "mach-o-universal":
@@ -42,11 +41,7 @@ export const inventoryLimitations = (
reader: ArtifactReader | undefined,
): string[] => {
if (reader !== undefined)
return reader.format === "zip" ||
reader.format === "ipa" ||
reader.format === "apk" ||
reader.format === "msix" ||
reader.format === "appx"
return isZipPackageFormat(reader.format)
? [ZIP_NON_ENTRY_TAIL_LIMITATION]
: [];
// dmg and pkg reach here only after classifyRootFormat matched their bytes.
+17
View File
@@ -8,6 +8,7 @@ import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { androidApplicationProjectionInputSchema } from "../domain/android/androidApplication.js";
import { appleApplicationProjectionInputSchema } from "../domain/apple/appleApplication.js";
import { harmonyApplicationProjectionInputSchema } from "../domain/harmony/harmonyApplication.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import type { Logger } from "pino";
import { traceApplicationFeatureInputSchema } from "../domain/javascript/javascriptFeatureTraceSchemas.js";
@@ -124,6 +125,22 @@ export const registerApplicationCommands = (
: result;
},
});
registerJsonCommand({
cli,
logger,
name: CLI_COMMANDS.projectHarmonyApplicationGraph,
description:
"Project authenticated HarmonyOS HAP, HSP, or App Pack inventory Evidence into an application graph",
inputSchema: harmonyApplicationProjectionInputSchema,
workflow: async (input) => {
const { projectHarmonyApplicationEvidence } =
await import("../application/harmony/HarmonyApplicationService.js");
const result = projectHarmonyApplicationEvidence(input);
return result.ok
? { ok: true, value: jsonValueSchema.parse(result.value) }
: result;
},
});
};
const registerObligationLedgerCommand = (
+1
View File
@@ -128,6 +128,7 @@ export const CLI_COMMANDS = Object.freeze({
evaluateReconstructionCoverage: "evaluate-reconstruction-coverage",
projectAndroidApplicationGraph: "project-android-application-graph",
projectAppleApplicationGraph: "project-apple-application-graph",
projectHarmonyApplicationGraph: "project-harmony-application-graph",
});
/** Ordered primary CLI inventory; aliases are intentionally excluded. */
+24
View File
@@ -24,6 +24,10 @@ import {
appleApplicationProjectionInputSchema,
appleApplicationProjectionResultSchema,
} from "../domain/apple/appleApplication.js";
import {
harmonyApplicationProjectionInputSchema,
harmonyApplicationProjectionResultSchema,
} from "../domain/harmony/harmonyApplication.js";
import type { ToolContract } from "./toolContractTypes.js";
import { toolContractMetadata } from "./toolEffects.js";
import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js";
@@ -36,6 +40,7 @@ import { JAVASCRIPT_EXPORT_SHAPE_COMPARISON_EXAMPLE } from "./javascript/javascr
import {
ANDROID_APPLICATION_GRAPH_EXAMPLE,
APPLE_APPLICATION_GRAPH_EXAMPLE,
HARMONY_APPLICATION_GRAPH_EXAMPLE,
MACOS_APPLICATION_GRAPH_EXAMPLE,
} from "./mobileApplicationGraphExamples.js";
@@ -296,6 +301,22 @@ export const APPLICATION_TOOL_CONTRACTS = [
},
],
},
{
name: "project_harmony_application_graph",
...toolContractMetadata("project_harmony_application_graph"),
description:
"Project authenticated HarmonyOS HAP, HSP, or App Pack inventory Evidence into an execution-free application inventory. Reports packaging-model hints (Stage module.json versus FA config.json), exact component paths and hashes (manifests, Ark bytecode, resources, native libraries, JavaScript, signing), App Pack child packages, runtime-family hints, and path-based N-API bridge hypotheses without decoding Ark bytecode, parsing manifest semantics, or claiming observed runtime calls.",
kind: "application",
inputSchema: harmonyApplicationProjectionInputSchema,
outputSchema: evidenceResultOf(harmonyApplicationProjectionResultSchema),
examples: [
{
title:
"Project HAP inventory Evidence into a HarmonyOS application graph",
input: HARMONY_APPLICATION_GRAPH_EXAMPLE,
},
],
},
] as const satisfies readonly ToolContract[];
/** Resolve one named application contract without relying on array position. */
@@ -326,6 +347,9 @@ export function applicationToolContract(
export function applicationToolContract(
name: "project_apple_application_graph",
): (typeof APPLICATION_TOOL_CONTRACTS)[8];
export function applicationToolContract(
name: "project_harmony_application_graph",
): (typeof APPLICATION_TOOL_CONTRACTS)[9];
export function applicationToolContract(
name: (typeof APPLICATION_TOOL_CONTRACTS)[number]["name"],
): (typeof APPLICATION_TOOL_CONTRACTS)[number] {
@@ -2,7 +2,10 @@ import { digestCanonicalValue } from "../domain/canonicalDigest.js";
import { createEvidence } from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
const inventory = (format: "apk" | "ipa" | "directory", digit: string) => {
const inventory = (
format: "apk" | "ipa" | "directory" | "hap",
digit: string,
) => {
const sha = digit.repeat(64);
const artifactId = `art_${digestCanonicalValue({ sha256: sha }, "Artifact inventory")}`;
const occurrenceId = `occ_${digestCanonicalValue(
@@ -129,3 +132,20 @@ export const MACOS_APPLICATION_GRAPH_EXAMPLE = {
),
],
};
/** Catalog example for HarmonyOS application inventory projection. */
export const HARMONY_APPLICATION_GRAPH_EXAMPLE = {
inventory_evidence: [
createEvidence(
{ path: "Fixture.hap", sha256: "d".repeat(64), format: "hap" },
provider,
{
operation: "inventory_artifact",
parameters: {},
result: inventory("hap", "d"),
confidence: "observed",
authority: "shipped-artifact",
},
),
],
};
+1
View File
@@ -457,6 +457,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
evaluate_reconstruction_coverage: effects(),
project_android_application_graph: evidence,
project_apple_application_graph: evidence,
project_harmony_application_graph: evidence,
open_binary: effects({ mutatesSession: true, launchesProcess: true }),
close_binary: effects({
mutatesSession: true,
+3
View File
@@ -53,6 +53,9 @@ const formatSchema = z.enum([
"apk",
"msix",
"appx",
"hap",
"hsp",
"app-pack",
"asar",
"dmg",
"pkg",
+31 -70
View File
@@ -1,31 +1,28 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import { parseArtifactInventoryEvidence } from "../artifactInventoryEvidence.js";
import { evidenceSchema } from "../evidence.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
import {
bridgeCandidateCoverageSchema,
projectCartesianCandidates,
} from "../bridgeCandidateProjection.js";
import { nativeRuntimeConvention } from "../nativeConvention.js";
import {
applicationInventoryProjectionInputSchema,
bridgeCandidateCoverageSchema,
compareProjectionStrings,
projectCartesianCandidates,
projectedBridgeCandidateSchema,
projectedComponentSchema,
projectedComponents,
projectionCoverage,
projectionDigest,
projectionEvidenceIdSchema,
} from "../mobileApplicationGraphProjection.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const pathSchema = z.string().min(1);
const componentSchema = z.strictObject({
path: pathSchema,
artifact_id: prefixedDigestSchema("art"),
sha256: digestSchema,
format: z.string().min(1),
});
const evidenceIdSchema = projectionEvidenceIdSchema;
const componentSchema = projectedComponentSchema;
/** Authenticated APK inventory pages projected as one Android application. */
export const androidApplicationProjectionInputSchema = z.strictObject({
inventory_evidence: z.array(evidenceSchema).min(1),
});
export const androidApplicationProjectionInputSchema =
applicationInventoryProjectionInputSchema;
/** Deterministic, execution-free Android application inventory projection. */
export const androidApplicationProjectionResultSchema = z.strictObject({
@@ -54,17 +51,13 @@ export const androidApplicationProjectionResultSchema = z.strictObject({
]),
),
bridge_candidates: z.array(
z.strictObject({
managed_path: pathSchema,
native_path: pathSchema,
basis: z.enum([
"managed-and-native-content",
"jni-library-convention",
"react-native-convention",
"flutter-convention",
"unity-convention",
]),
}),
projectedBridgeCandidateSchema([
"managed-and-native-content",
"jni-library-convention",
"react-native-convention",
"flutter-convention",
"unity-convention",
] as const),
),
bridge_candidate_coverage: bridgeCandidateCoverageSchema,
coverage: z.strictObject({
@@ -94,27 +87,7 @@ export const projectAndroidApplication = (
throw new TypeError(
`Android application projection requires APK inventory Evidence; the inventory root format is ${inventory.manifest.root_format}. APK is chosen for a ZIP archive whose name ends in .apk.`,
);
const nodes = new Map(
inventory.nodes.map((node) => [node.artifact_id, node]),
);
const all = inventory.occurrences
.filter(
(occurrence) =>
occurrence.artifact_id !== null && occurrence.logical_path !== ".",
)
.map((occurrence) => {
const node = nodes.get(occurrence.artifact_id ?? "");
if (node === undefined)
throw new TypeError(
"Android application occurrence has no artifact node",
);
return {
path: occurrence.logical_path,
artifact_id: node.artifact_id,
sha256: node.sha256,
format: occurrence.artifact_format,
} satisfies Component;
});
const all = projectedComponents(inventory);
const classified = classify(all);
const bridgeProjection = bridgeCandidates(
[...classified.dex, ...classified.jvm_classes],
@@ -146,23 +119,20 @@ export const projectAndroidApplication = (
root_format: "apk" as const,
source_evidence_ids: evidence
.map(({ evidence_id: id }) => id)
.sort(compare),
.sort(compareProjectionStrings),
components,
runtime_families: runtimeFamilies(all),
bridge_candidates: bridgeProjection.candidates,
bridge_candidate_coverage: bridgeProjection.coverage,
coverage: {
status:
inventory.complete && bridgeProjection.coverage.status === "complete"
? ("complete-within-inventory" as const)
: ("partial" as const),
inventory_complete: inventory.complete,
},
coverage: projectionCoverage(
inventory,
bridgeProjection.coverage.status === "complete",
),
limitations,
};
return androidApplicationProjectionResultSchema.parse({
...withoutId,
projection_id: `adp_${digest(withoutId)}`,
projection_id: `adp_${projectionDigest(withoutId, "Android application projection")}`,
});
};
@@ -198,7 +168,7 @@ const runtimeFamilies = (all: readonly Component[]) => {
const convention = nativeRuntimeConvention(path);
if (convention !== null) families.add(convention);
}
return [...families].sort(compare);
return [...families].sort(compareProjectionStrings);
};
const bridgeCandidates = (
@@ -226,12 +196,3 @@ const bridgeBasis = (
return "jni-library-convention";
return "managed-and-native-content";
};
const compare = (left: string, right: string): number =>
left < right ? -1 : left > right ? 1 : 0;
const digest = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError("Android application projection is not canonical JSON");
return createHash("sha256").update(encoded).digest("hex");
};
+7 -11
View File
@@ -1,6 +1,3 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import {
@@ -28,6 +25,10 @@ import {
bridgeCandidateCoverageSchema,
projectCartesianCandidates,
} from "../bridgeCandidateProjection.js";
import {
compareProjectionStrings,
projectionDigest,
} from "../mobileApplicationGraphProjection.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const pathSchema = z.string().min(1);
@@ -437,11 +438,6 @@ const projectionLimitations = (facts: {
"A bridge basis is inferred from the native path and is repeated for every managed component.",
];
const compare = (left: string, right: string): number =>
left < right ? -1 : left > right ? 1 : 0;
const digest = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError("Apple application projection is not canonical JSON");
return createHash("sha256").update(encoded).digest("hex");
};
const compare = compareProjectionStrings;
const digest = (value: unknown): string =>
projectionDigest(value, "Apple application projection");
+3
View File
@@ -56,6 +56,9 @@ const artifactFormatSchema = z.enum([
"apk",
"msix",
"appx",
"hap",
"hsp",
"app-pack",
"plist",
"entitlements",
"directory",
+3
View File
@@ -102,6 +102,9 @@ export type BinaryTarget =
| "apk"
| "msix"
| "appx"
| "hap"
| "hsp"
| "app-pack"
| "asar"
| "dmg"
| "pkg";
+3
View File
@@ -48,6 +48,9 @@ const subjectSchema = z.object({
"apk",
"msix",
"appx",
"hap",
"hsp",
"app-pack",
"asar",
"dmg",
"pkg",
+246
View File
@@ -0,0 +1,246 @@
import { z } from "zod";
import { parseArtifactInventoryEvidence } from "../artifactInventoryEvidence.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
import { nativeRuntimeConvention } from "../nativeConvention.js";
import {
applicationInventoryProjectionInputSchema,
bridgeCandidateCoverageSchema,
compareProjectionStrings,
projectCartesianCandidates,
projectedBridgeCandidateSchema,
projectedComponentSchema,
projectedComponents,
projectionCoverage,
projectionDigest,
projectionEvidenceIdSchema,
projectionPathSchema,
} from "../mobileApplicationGraphProjection.js";
const evidenceIdSchema = projectionEvidenceIdSchema;
const componentSchema = projectedComponentSchema;
const HARMONY_ROOT_FORMATS = ["hap", "hsp", "app-pack"] as const;
type RootFormat = (typeof HARMONY_ROOT_FORMATS)[number];
/** Authenticated HarmonyOS inventory pages projected as one application. */
export const harmonyApplicationProjectionInputSchema =
applicationInventoryProjectionInputSchema;
/** Deterministic, execution-free HarmonyOS application inventory projection. */
export const harmonyApplicationProjectionResultSchema = z.strictObject({
projection_id: prefixedDigestSchema("hmp"),
root_sha256: digestSchema,
root_format: z.enum(HARMONY_ROOT_FORMATS),
source_evidence_ids: z.array(evidenceIdSchema).min(1),
packaging_model: z.enum(["stage", "fa", "unknown"]),
components: z.strictObject({
manifests: z.array(componentSchema),
bytecode: z.array(componentSchema),
resources: z.array(componentSchema),
native_libraries: z.array(componentSchema),
javascript: z.array(componentSchema),
signing: z.array(componentSchema),
}),
unavailable_components: z.array(
z.strictObject({
path: projectionPathSchema,
artifact_id: z.null(),
sha256: z.null(),
format: z.string().min(1),
encrypted: z.boolean(),
limitations: z.array(z.string()),
}),
),
app_pack_children: z.array(componentSchema),
runtime_families: z.array(
z.enum(["ark", "native", "javascript", "react-native", "flutter", "unity"]),
),
bridge_candidates: z.array(
projectedBridgeCandidateSchema([
"managed-and-native-content",
"napi-library-convention",
] as const),
),
bridge_candidate_coverage: bridgeCandidateCoverageSchema,
coverage: z.strictObject({
status: z.enum(["complete-within-inventory", "partial"]),
inventory_complete: z.boolean(),
}),
limitations: z.array(z.string().min(1)),
});
export type HarmonyApplicationProjectionInput = z.infer<
typeof harmonyApplicationProjectionInputSchema
>;
export type HarmonyApplicationProjectionResult = z.infer<
typeof harmonyApplicationProjectionResultSchema
>;
type Component = z.infer<typeof componentSchema>;
/** Project exact HarmonyOS package paths and hashes without decoding or executing target code. */
export const projectHarmonyApplication = (
input: HarmonyApplicationProjectionInput,
): HarmonyApplicationProjectionResult => {
const parsed = harmonyApplicationProjectionInputSchema.parse(input);
const { evidence, inventory } = parseArtifactInventoryEvidence(
parsed.inventory_evidence,
);
const rootFormat = harmonyRootFormat(inventory.manifest.root_format);
const all = projectedComponents(inventory);
const unavailable = inventory.occurrences
.filter(
(occurrence) =>
occurrence.logical_path !== "." && occurrence.artifact_id === null,
)
.map((occurrence) => ({
path: occurrence.logical_path,
artifact_id: null,
sha256: null,
format: occurrence.artifact_format,
encrypted: occurrence.encrypted,
limitations: occurrence.limitations,
}));
const classified = classify(all);
const bridgeProjection = bridgeCandidates(
classified.bytecode,
classified.native_libraries,
);
const limitations = [
...(!inventory.complete
? ["Source inventory pages are incomplete; absence is unknown."]
: []),
...(unavailable.length > 0
? [
"Some inventoried occurrences have no authenticated content identity. Their paths and limitations are retained in unavailable_components; component and runtime absence is unknown.",
]
: []),
"Manifest, module, resource, and signing semantics require a dedicated HarmonyOS provider; this projection reports exact inventory paths and hashes only.",
"The packaging model is a path-presence heuristic: a Stage model is claimed only from module.json and a FA model only from config.json; both can coexist with unusual layouts.",
"Runtime families are inferred from inventory formats and paths; filename suffixes do not establish valid Ark bytecode.",
"The signing component lists META-INF certificate-entry suffixes only; signatures applied by the packaging tool live in the ZIP signing block rather than archive entries, so an empty signing list does not mean the package is unsigned.",
"Bridge candidates are path-based hypotheses, not decoded N-API declarations or observed runtime calls.",
...(rootFormat === "app-pack"
? [
"App Pack child packages are listed by inventory path only; their contents are not recursively inventoried by this projection.",
"The app-pack root classification is a verified-ZIP-magic plus .app suffix rule; the projection does not require pack.info or child packages before reporting the root format.",
]
: []),
"HarmonyOS .har shared libraries are not identified by this projection; the .har suffix also names HTTP Archive JSON, so that classification requires verified ZIP bytes.",
...(bridgeProjection.coverage.status === "partial"
? [
`Bridge candidate pairs exceeded the projection safety budget; ${bridgeProjection.coverage.omitted_candidates} hypotheses are omitted. Component arrays still include every component from the supplied inventory pages.`,
]
: []),
];
const withoutId = {
root_sha256: inventory.manifest.root_sha256,
root_format: rootFormat,
source_evidence_ids: evidence
.map(({ evidence_id: id }) => id)
.sort(compareProjectionStrings),
packaging_model: packagingModel(classified.manifests),
components: classified,
unavailable_components: unavailable,
app_pack_children:
rootFormat === "app-pack"
? all.filter(({ path }) => /\.(?:hap|hsp)$/iu.test(path))
: [],
runtime_families: runtimeFamilies(all),
bridge_candidates: bridgeProjection.candidates,
bridge_candidate_coverage: bridgeProjection.coverage,
coverage: projectionCoverage(
inventory,
bridgeProjection.coverage.status === "complete" &&
unavailable.length === 0,
),
limitations,
};
return harmonyApplicationProjectionResultSchema.parse({
...withoutId,
projection_id: `hmp_${projectionDigest(withoutId, "HarmonyOS application projection")}`,
});
};
const harmonyRootFormat = (format: string): RootFormat => {
const root = HARMONY_ROOT_FORMATS.find((candidate) => candidate === format);
if (root === undefined)
throw new TypeError(
`HarmonyOS application projection requires HAP, HSP, or App Pack inventory Evidence (got ${format})`,
);
return root;
};
const packagingModel = (
manifests: readonly Component[],
): HarmonyApplicationProjectionResult["packaging_model"] => {
const stage = manifests.some(({ path }) =>
/(?:^|\/)module\.json$/iu.test(path),
);
const fa = manifests.some(({ path }) => /(?:^|\/)config\.json$/iu.test(path));
if (stage) return "stage";
if (fa) return "fa";
return "unknown";
};
const classify = (all: readonly Component[]) => ({
manifests: all.filter(({ path }) =>
/(?:^|\/)(?:module\.json|config\.json|pack\.info)$/iu.test(path),
),
bytecode: all.filter(({ path }) => /\.(?:abc|pa)$/iu.test(path)),
resources: all.filter(
({ path }) =>
/(?:^|\/)resources\.index$/iu.test(path) ||
/^(?:resources\/|assets\/[^/]+\/resources\/)/iu.test(path),
),
native_libraries: all.filter(
({ path, format }) =>
format === "elf" || /(?:^|\/)libs\/[^/]+\/[^/]+\.so$/iu.test(path),
),
javascript: all.filter(
({ path, format }) =>
format === "javascript-bundle" || /\.(?:m?js|cjs)$/iu.test(path),
),
signing: all.filter(({ path }) =>
/^META-INF\/[^/]+\.(?:p7b|sig|cer|crt|pem|provision)$/iu.test(path),
),
});
const runtimeFamilies = (all: readonly Component[]) => {
const paths = all.map(({ path }) => path.toLowerCase());
const families = new Set<
HarmonyApplicationProjectionResult["runtime_families"][number]
>();
if (paths.some((path) => path.endsWith(".abc") || path.endsWith(".pa")))
families.add("ark");
if (all.some(({ format }) => format === "elf")) families.add("native");
if (paths.some((path) => /\.(?:m?js|cjs)$/.test(path)))
families.add("javascript");
for (const { path } of all) {
const convention = nativeRuntimeConvention(path);
if (convention !== null) families.add(convention);
}
return [...families].sort(compareProjectionStrings);
};
const bridgeCandidates = (
managed: readonly Component[],
native: readonly Component[],
) => {
return projectCartesianCandidates({
groups: [{ left: managed, right: native }],
createCandidate: (managed_path, target) => ({
managed_path,
native_path: target.path,
basis: napiBasis(target.path),
}),
});
};
const napiBasis = (
path: string,
): HarmonyApplicationProjectionResult["bridge_candidates"][number]["basis"] =>
/(?:^|\/)libs\/[^/]+\/lib[^/]+\.so$/iu.test(path)
? "napi-library-convention"
: "managed-and-native-content";
@@ -0,0 +1,102 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import type { ParsedInventorySet } from "./artifactInventoryEvidence.js";
import { evidenceSchema } from "./evidence.js";
import { digestSchema } from "./digests.js";
import { prefixedDigestSchema } from "./digests.js";
import {
bridgeCandidateCoverageSchema,
projectCartesianCandidates,
} from "./bridgeCandidateProjection.js";
/** Evidence-scoped identifier schemas shared by application graph projections. */
export const projectionEvidenceIdSchema = prefixedDigestSchema("ev");
export const projectionPathSchema = z.string().min(1);
/** Inventory pages accepted by every application graph projection. */
export const applicationInventoryProjectionInputSchema = z.strictObject({
inventory_evidence: z.array(evidenceSchema).min(1),
});
/** One authenticated inventory entry retained by application graph projections. */
export const projectedComponentSchema = z.strictObject({
path: projectionPathSchema,
artifact_id: prefixedDigestSchema("art"),
sha256: digestSchema,
format: z.string().min(1),
});
export type ProjectedComponent = z.infer<typeof projectedComponentSchema>;
/** Path-pair hypotheses connecting managed content to a native library. */
export const projectedBridgeCandidateSchema = <
Basis extends readonly [string, ...string[]],
>(
basis: Basis,
) =>
z.strictObject({
managed_path: projectionPathSchema,
native_path: projectionPathSchema,
basis: z.enum(basis),
});
/** Coverage status combining inventory completeness with a projection budget. */
export const projectionCoverage = (
inventory: ParsedInventorySet["inventory"],
budgetComplete: boolean,
): {
status: "complete-within-inventory" | "partial";
inventory_complete: boolean;
} => ({
status:
inventory.complete && budgetComplete
? ("complete-within-inventory" as const)
: ("partial" as const),
inventory_complete: inventory.complete,
});
/** Flatten every inventoried occurrence into authenticated path components. */
export const projectedComponents = (
inventory: ParsedInventorySet["inventory"],
): ProjectedComponent[] => {
const nodes = new Map(
inventory.nodes.map((node) => [node.artifact_id, node]),
);
return inventory.occurrences
.filter(
(occurrence) =>
occurrence.artifact_id !== null && occurrence.logical_path !== ".",
)
.map((occurrence) => {
const node = nodes.get(occurrence.artifact_id ?? "");
if (node === undefined)
throw new TypeError(
"Application projection occurrence has no artifact node",
);
return {
path: occurrence.logical_path,
artifact_id: node.artifact_id,
sha256: node.sha256,
format: occurrence.artifact_format,
} satisfies ProjectedComponent;
});
};
export { bridgeCandidateCoverageSchema, projectCartesianCandidates };
/** Unicode code point ordering so projection arrays sort deterministically. */
export const compareProjectionStrings = (
left: string,
right: string,
): number => (left < right ? -1 : left > right ? 1 : 0);
/** Digest a canonical JSON projection payload for its stable identifier. */
export const projectionDigest = (value: unknown, label: string): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError(`${label} is not canonical JSON`);
return createHash("sha256").update(encoded).digest("hex");
};
+25 -2
View File
@@ -1,5 +1,21 @@
/** ZIP-backed application package families that share the hardened archive reader. */
export type ZipPackageFormat = "zip" | "ipa" | "apk" | "msix" | "appx";
export const ZIP_PACKAGE_FORMATS = [
"zip",
"ipa",
"apk",
"msix",
"appx",
"hap",
"hsp",
"app-pack",
] as const;
export type ZipPackageFormat = (typeof ZIP_PACKAGE_FORMATS)[number];
/** All ZIP package families share archive ownership and inventory coverage. */
export const isZipPackageFormat = (
format: string,
): format is ZipPackageFormat =>
ZIP_PACKAGE_FORMATS.some((candidate) => candidate === format);
/** Recognize local-header, empty-archive, or split-archive ZIP signatures, not archive validity. */
export const hasZipSignature = (bytes: Uint8Array): boolean =>
@@ -14,7 +30,12 @@ export const hasZipSignature = (bytes: Uint8Array): boolean =>
* Classify a ZIP-backed package by its complete lower-cased path suffix.
*
* This is deliberately extension-only. Callers must separately verify ZIP
* magic before trusting the classification for a root input.
* magic before trusting the classification for a root input. HarmonyOS `.har`
* is intentionally absent: the suffix also names HTTP Archive JSON, so a
* Harmony shared archive is only established from verified ZIP bytes. The
* HarmonyOS App Pack suffix `.app` is also absent here: it applies only to
* root inputs (see `classifyAndHashRoot`), because a nested ZIP entry ending
* in `.app` inside another package, such as an IPA, is not an App Pack.
*/
export const zipPackageFormatForPath = (
path: string,
@@ -26,6 +47,8 @@ export const zipPackageFormatForPath = (
if (lower.endsWith(".apk")) return "apk";
if (lower.endsWith(".msix") || lower.endsWith(".msixbundle")) return "msix";
if (lower.endsWith(".appx") || lower.endsWith(".appxbundle")) return "appx";
if (lower.endsWith(".hap")) return "hap";
if (lower.endsWith(".hsp")) return "hsp";
return undefined;
};
@@ -4,6 +4,7 @@ import { runAdmittedToolOperation } from "../admittedToolOperation.js";
import { projectAndroidApplicationEvidence } from "../../application/android/AndroidApplicationService.js";
import { projectAppleApplicationEvidence } from "../../application/apple/AppleApplicationService.js";
import { projectHarmonyApplicationEvidence } from "../../application/harmony/HarmonyApplicationService.js";
import {
APPLICATION_TOOL_CONTRACTS,
applicationToolContract,
@@ -17,7 +18,7 @@ import { toolRegistrationOptions } from "../toolRegistrationOptions.js";
import { recordResult } from "./helpers.js";
import type { ApplicationToolRegistration } from "./types.js";
/** Register execution-free Android and Apple inventory projection tools. */
/** Register execution-free mobile application inventory projection tools. */
export const registerProjectMobileApplicationGraphTools = (
server: EvidenceMcpServer,
options: ApplicationToolRegistration,
@@ -34,6 +35,12 @@ export const registerProjectMobileApplicationGraphTools = (
contract: applicationToolContract("project_apple_application_graph"),
project: projectAppleApplicationEvidence,
});
registerProjection({
server,
options,
contract: applicationToolContract("project_harmony_application_graph"),
project: projectHarmonyApplicationEvidence,
});
};
const registerProjection = (context: {