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
+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;
};