Files
reverse-engineering-anything/tests/boundary/filesystem/harmony/application.test.ts
T
morluto 1f24b3fa57 feat(evidence)!: name the Evidence subject by its target identity (format revision 2) (#11416)
* feat(evidence)!: name the Evidence subject by its target identity (format revision 2)

The Evidence subject carries subject.identity (kind, sha256, format,
architecture, selection) and the Evidence ID commits to it, so raw/DOL
entry points and ESP flash offsets of the same bytes are different
subjects. Every record declares evidence_format: 2; revision 1 bundles,
standalone records and snapshots are refused with the recreate guidance.
binaryTargetIdentity is the one projection of an open target, used by
Evidence and snapshot comparison.

BREAKING CHANGE: Evidence format revision 2. Evidence IDs commit to the
subject's target identity (subject.identity, including the raw/DOL entry
point or ESP flash offsets), and every record declares evidence_format: 2.
Evidence bundles, records and analysis snapshots from earlier releases are
refused; recreate the observations with this release.

* refactor(analysis-view): read parent subjects through the Evidence identity accessors (#11423)

Analysis views compare their parent's file identity (evidenceFileTarget)
and take path and digest from evidenceSubjectTarget instead of reading
the subject's digest, format and architecture members, which duplicate
subject.identity until they are removed. A counted guard
(evidence-subject-declaration-read) keeps new direct reads out and
records the 20 remaining files.

* fix(evidence): carry format refusals through Evidence readers and bind target selections

- safeParseEvidence/safeParseImmutableEvidence return the format refusal as
  an expected failure; every consumer maps it to the one integrity refusal
  with the recreate guidance. An unmarked object is an earlier record only
  when it has every member records have always carried.
- ArtifactProvider inventory roots and provider subjects that name the
  target's own bytes carry the target's selection (ESP flash offsets).
- Snapshot rows bind only Evidence whose identity, selection included,
  matches the snapshot target.
- Entry-point selections use the raw-binary entry point form.

* fix(evidence): refuse unauthenticated or earlier-format records instead of reading them as absent

- recognizeEvidence (evidenceValidation) replaces tryParseEvidence: input
  without an evidence_id is not Evidence (ok(undefined)); a record that names
  one but fails authentication or is from another format revision is an
  EvidenceIntegrityError carrying the recreate guidance, never undefined.
- Direct analysis retains that refusal as a secondary failure instead of
  silently skipping source capture; cleanup projection, source-closure
  annotation and the flutter, debugger and release-exposure recoveries use
  the same owner (the last three previously read the unauthenticated schema).
- A desktop capture.json from an earlier format is refused with the recreate
  guidance instead of "not desktop application capture Evidence".

* fix(evidence): advertise revision 2 ledger examples and rank delivery omissions by serialized size

- The obligation ledger and reconstruction coverage examples named
  evidence_format 1, which revision 2 refuses; they now use
  EVIDENCE_FORMAT_REVISION.
- MCP delivery chose which unretained recovery to omit by a parsed-storage
  lower bound clipped at the response budget. Once revision 2 subjects made
  the source record's estimate cross the budget, both candidates tied at the
  clip and the smaller source was omitted ahead of the larger completed
  observation. Candidates are now ranked by serialized size, which is what
  the budget counts.

* refactor(native): compare function snapshots by their Evidence target identity (#11450)

Function snapshots carry the subject's file target identity instead of the
duplicated subject declaration. Call paths and function comparisons compare
targets through sameTargetIdentity, so the same bytes opened at a different
raw entry point or ESP flash offset no longer count as one coordinate space:
build_call_path refuses the mix, and compare_functions no longer matches
entries by address across selections. Structural candidates and native
function matching read the architecture and digest through
evidenceFileTarget.

Refs #11417

* refactor(artifacts): compare artifact and WASM summaries by their Evidence target identity (#11461)

Artifact comparison authenticates a summary against its retained inventory
through sameTargetIdentity and rebinds the alias with the whole target,
selection included, so a flash-selected inventory summary taken under an
alias path is no longer refused. WASM comparison, the analysis view
artifact projection and the inventory root check read the digest, format
and display path through the Evidence identity accessors.

Refs #11417

* refactor(evidence): read record subjects through the identity accessors in JS, managed, ledger and bundle readers (#11470)

JavaScript application graphs, runtime reconciliation, managed inspection
and native verification sources, the record summary filter, the ledger's
residual-unknown target and bundle scope selection read the subject digest,
format and display path through evidenceFileTarget and
evidenceSubjectDisplay. No comparison changes: each reader matches one
record's facts against its own payload or a caller filter.

Refs #11417

* refactor(evidence)!: name the Evidence subject only by its target identity (#11497)

* refactor(evidence)!: name the Evidence subject only by its target identity

The subject keeps `identity` and the display facts `name` and `local_path`.
The duplicated `digest`, `format` and `architecture` members are removed; the
format-owned declaration now validates the identity itself. Readers the type
checker found move to the owner accessors; untyped reads in verify scripts,
the efficiency harness and test matchers move to `subject.identity`. The
`evidence-subject-declaration-read` text guard and its baseline are deleted.

Fixes #11473
Refs #11417

BREAKING CHANGE: the Evidence subject no longer has `digest`, `format` or
`architecture`; read `subject.identity.sha256`, `subject.identity.format` and
`subject.identity.architecture`. A record that still carries them is refused.

* test(evidence): give the Flutter verifier fixture the identity subject and check the DOL declaration without the ID

* test(evidence): drop the removed subject members from the declaration matrix and tamper fixtures

* feat(evidence)!: give every Evidence record an explicit subject identity (#11536)

* feat(evidence)!: give every Evidence record an explicit subject identity

A producer that cannot name a file passes an `unknown` target identity
with a closed reason (derived-from-linked-evidence, not-observed,
unsupported-subject) instead of no subject. The subject is non-null;
unknown subjects have no display facts. The generic missing-subject
limitation and `subjectUnavailableReason` are removed; producer-specific
explanations are ordinary limitations. Comparison identity requires the
derived unknown, and null-subject consumers ask the owner accessors.

Refs #11417

BREAKING CHANGE: every Evidence record has a subject. A record without a
file target names `subject.identity` `{ "kind": "unknown", "reason": … }`
with `name` and `local_path` null, instead of `subject: null` and the
limitation "Artifact identity is unavailable for this observation.".
Their Evidence IDs change.

* fix(evidence): name explicit unknown subjects in JavaScript callers and keep a managed graph's file subject

The verification scripts are not type-checked, so five createEvidence
callers still passed undefined (or a missing first target) after the subject
became required. They now pass unknownTarget("not-observed").

A managed application graph chose the first present input subject. Every
subject is now present, so an unknown artifact subject hid a file subject on
the member or boundary Evidence. The graph now takes the first input subject
that names a file.

* test(evidence): assert the subject kind instead of a presence the type now guarantees

Every Evidence record has a subject after this change, so test guards and
assertions that checked it for null always passed. Each now checks that the
fixture subject names a file, or is removed where a later fileIdentity,
fileSubjectTarget or fileSubjectDisplay call already requires that. Non-null
assertions on Evidence subjects are removed; analysis-view inputs, whose
subject is optional, keep an undefined check.

* test(evidence): expect the Evidence subject format under its identity

Two boundary tests still matched subject.format, which slice 2e moved into
subject.identity. toMatchObject is not type-checked against the Evidence
shape, so they failed only when run (the signature test on macOS).
2026-11-16 06:28:01 +08:00

676 lines
25 KiB
TypeScript

import {
fileIdentity,
fileSubjectDisplay,
} from "../../../fixtures/evidenceSubject.js";
import { projectCliAnalysisResult } from "../../../../src/cli/projectCliAnalysisResult.js";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { minimalElfImage } from "../../../fixtures/nativeHeaders.js";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { fragmentInventoryEvidence } from "../../../fixtures/artifactEvidence.js";
import {
createNonApplicationZipInventory,
inventoryApplicationPackage,
requireDeterministicProjection,
requireSuccessfulProjection,
writeApplicationZip,
} from "../../../support/applicationSessionFixture.js";
import { projectHarmonyApplicationEvidence } from "../../../../src/application/harmony/HarmonyApplicationService.js";
import { createDirectAnalysis } from "../../../../src/composition/directAnalysis.js";
import {
harmonyApplicationProjectionResultSchema,
type HarmonyApplicationProjectionResult,
} from "../../../../src/domain/harmony/harmonyApplication.js";
import { artifactInventoryResultSchema } from "../../../../src/domain/artifactGraph.js";
import { createEvidence } from "../../../../src/domain/evidence.js";
import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResolver.js";
import {
ZIP_PACKAGE_FORMATS,
ZIP_NON_ENTRY_LIMITATION,
} from "../../../../src/domain/zipPackageFormat.js";
const { runProviderAnalysis } = createDirectAnalysis({});
const elf = Uint8Array.from(minimalElfImage());
const stageHapEntries = [
{ path: "module.json", content: '{"module":{"name":"entry"}}' },
{ path: "ets/modules.abc", content: "panda bytecode" },
{ path: "libs/arm64-v8a/libentry.so", content: elf },
{ path: "resources.index", content: "resource index" },
{ path: "resources/base/profile/main_pages.json", content: "{}" },
{ path: "assets/web/index.js", content: "bridge();" },
{ path: "META-INF/FIXTURE.p7b", content: "opaque signing" },
] as const;
const PKG_CONTEXT_NAME = "pkgContextInfo.json";
const unreadDeclarationLimitations = (
limitations: readonly string[],
): string[] => limitations.filter((text) => text.includes(PKG_CONTEXT_NAME));
const projectStageHap = async (
label: string,
entries: readonly { path: string; content: string | Uint8Array }[],
): Promise<HarmonyApplicationProjectionResult> => {
const path = await writeApplicationZip(label, "Fixture.hap", entries);
return requireDeterministicProjection(
projectHarmonyApplicationEvidence,
await inventoryApplicationPackage(path),
harmonyApplicationProjectionResultSchema,
);
};
const stageHapWithDeclaration = stageHapEntries.map(({ path, content }) => ({
path,
content,
}));
describe("HarmonyOS N-API declaration disclosure", () => {
it("discloses the unread declaration by its names, not its wording", async () => {
const projection = await projectStageHap("rea-harmony-pkg-context-", [
...stageHapWithDeclaration,
{
path: PKG_CONTEXT_NAME,
content: '{"libentry.so":{"isSO":true}}',
},
]);
const control = await projectStageHap(
"rea-harmony-pkg-context-control-",
stageHapWithDeclaration,
);
const disclosed = unreadDeclarationLimitations(projection.limitations);
expect(disclosed).toHaveLength(1);
expect(disclosed[0]).toContain("bridge_candidates");
expect(disclosed[0]).toMatch(/\bisSO\b/);
expect(disclosed[0]).toMatch(/not read|not narrowed/iu);
expect(projection.bridge_candidates).toEqual(control.bridge_candidates);
expect(unreadDeclarationLimitations(control.limitations)).toEqual([]);
});
});
describe("HarmonyOS unclassified inventory", () => {
it("retains distinct unclassified paths sharing content with a classified file", async () => {
const path = await writeApplicationZip(
"rea-harmony-unclassified-",
"Fixture.hap",
[
{ path: "module.json", content: "{}" },
{ path: "pkgContextInfo.json", content: "{}" },
{ path: ".pages.info", content: "{}" },
{ path: "metadata-copy.json", content: "{}" },
{ path: "resources/base/bridge.js", content: "bridge();" },
],
);
const inventory = await inventoryApplicationPackage(path);
const original = JSON.stringify(inventory);
const projection = requireDeterministicProjection(
projectHarmonyApplicationEvidence,
inventory,
harmonyApplicationProjectionResultSchema,
);
expect(projection.unclassified_components).toEqual([
expect.objectContaining({
path: ".pages.info",
sha256:
"44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a",
}),
expect.objectContaining({ path: "metadata-copy.json" }),
expect.objectContaining({ path: "pkgContextInfo.json" }),
]);
expect(projection.components.resources.map(({ path }) => path)).toEqual([
"resources/base/bridge.js",
]);
expect(projection.components.javascript.map(({ path }) => path)).toEqual([
"resources/base/bridge.js",
]);
expect(projection.coverage).toEqual({
status: "complete-within-inventory",
inventory_complete: true,
});
const pages = fragmentInventoryEvidence(inventory, 3);
const assembled = requireSuccessfulProjection(
projectHarmonyApplicationEvidence({
inventory_evidence: [...pages].reverse(),
}),
);
const fromPages = harmonyApplicationProjectionResultSchema.parse(
assembled.normalized_result,
);
expect(fromPages.unclassified_components).toEqual(
projection.unclassified_components,
);
expect(fromPages.coverage).toEqual(projection.coverage);
expect(JSON.stringify(inventory)).toBe(original);
});
});
it("retains inventoried certificate-block suffixes without claiming verified signatures", async () => {
const names = ["CERT.RSA", "CERT.DSA", "CERT.EC", "FIXTURE.p7b"];
const path = await writeApplicationZip(
"rea-harmony-certificate-paths-",
"Fixture.hap",
[
...names.map((name) => ({
path: `META-INF/${name}`,
content: "opaque bytes",
})),
{ path: "META-INF/MANIFEST.MF", content: "manifest" },
{ path: "META-INF/CERT.SF", content: "signature file" },
],
);
const graph = requireDeterministicProjection(
projectHarmonyApplicationEvidence,
await inventoryApplicationPackage(path),
harmonyApplicationProjectionResultSchema,
);
expect(graph.components.signing.map(({ path }) => path).sort()).toEqual(
names.map((name) => `META-INF/${name}`).sort(),
);
});
describe("HarmonyOS application projection", () => {
it.each(["js", "mjs", "cjs", "jsx", "ts", "tsx", "mts", "cts"])(
"retains the JavaScript runtime hint for an authenticated .%s component",
async (extension) => {
const member = `assets/js/index.${extension}`;
const path = await writeApplicationZip(
"rea-harmony-javascript-",
"Fixture.hap",
[{ path: member, content: "export const value = 1;" }],
);
const inventory = await inventoryApplicationPackage(path);
const projection = requireDeterministicProjection(
projectHarmonyApplicationEvidence,
inventory,
harmonyApplicationProjectionResultSchema,
);
expect(projection.components.javascript).toEqual([
expect.objectContaining({ path: member, format: "javascript-bundle" }),
]);
expect(projection.runtime_families).toEqual(["javascript"]);
expect(projection.coverage.status).toBe("complete-within-inventory");
},
);
it("does not infer JavaScript from unrelated inventory content", async () => {
const path = await writeApplicationZip(
"rea-harmony-no-javascript-",
"Fixture.hap",
[
{ path: "module.json", content: "{}" },
{ path: "assets/js/notes.txt", content: "ordinary text" },
],
);
const inventory = await inventoryApplicationPackage(path);
const projection = requireDeterministicProjection(
projectHarmonyApplicationEvidence,
inventory,
harmonyApplicationProjectionResultSchema,
);
expect(projection.components.javascript).toEqual([]);
expect(projection.runtime_families).toEqual([]);
});
it("projects deterministic Stage HAP components and explicit bridge hypotheses", async () => {
const path = await writeApplicationZip(
"rea-harmony-",
"Fixture.hap",
stageHapEntries,
);
const inventory = await inventoryApplicationPackage(path);
expect(fileIdentity(inventory.subject).format).toBe("hap");
const left = requireDeterministicProjection(
projectHarmonyApplicationEvidence,
inventory,
harmonyApplicationProjectionResultSchema,
);
expect(left).toMatchObject({
root_format: "hap",
packaging_model: "stage",
coverage: {
status: "complete-within-inventory",
inventory_complete: true,
},
});
expect(left.components.manifests.map(({ path }) => path)).toEqual([
"module.json",
]);
expect(left.components.bytecode.map(({ path }) => path)).toEqual([
"ets/modules.abc",
]);
expect(left.components.resources.map(({ path }) => path).sort()).toEqual([
"resources.index",
"resources/base/profile/main_pages.json",
]);
expect(left.components.native_libraries).toHaveLength(1);
expect(left.components.javascript).toHaveLength(1);
expect(left.components.signing).toHaveLength(1);
expect(left.runtime_families).toEqual(["ark", "javascript", "native"]);
expect(left.bridge_candidates).toEqual([
expect.objectContaining({
managed_path: "ets/modules.abc",
native_path: "libs/arm64-v8a/libentry.so",
basis: "napi-library-convention",
}),
]);
expect(left.app_pack_children).toEqual([]);
expect(left.unclassified_components).toEqual([]);
expect(JSON.stringify(left)).not.toContain("opaque signing");
expect(left.limitations).toContain(
"Manifest, module, resource, and signing semantics require a dedicated HarmonyOS provider; this projection reports exact inventory paths and hashes only.",
);
});
it("projects App Pack children by path without recursive inventory", async () => {
const entryHap = await writeApplicationZip(
"rea-harmony-entry-",
"entry.hap",
[
{ path: "module.json", content: '{"module":{}}' },
{ path: "ets/modules.abc", content: "panda" },
],
);
const featureHsp = await writeApplicationZip(
"rea-harmony-feature-",
"feature.hsp",
[{ path: "module.json", content: '{"module":{}}' }],
);
const path = await writeApplicationZip("rea-harmony-app-", "Bundle.app", [
{ path: "pack.info", content: '{"packages":[]}' },
{ path: "entry.hap", content: new Uint8Array(await readFile(entryHap)) },
{
path: "feature.hsp",
content: new Uint8Array(await readFile(featureHsp)),
},
]);
const inventory = await inventoryApplicationPackage(path);
expect(fileIdentity(inventory.subject).format).toBe("app-pack");
const projection = requireDeterministicProjection(
projectHarmonyApplicationEvidence,
inventory,
harmonyApplicationProjectionResultSchema,
);
expect(projection.root_format).toBe("app-pack");
expect(projection.components.manifests.map(({ path }) => path)).toEqual([
"pack.info",
]);
expect(projection.app_pack_children.map(({ path }) => path).sort()).toEqual(
["entry.hap", "feature.hsp"],
);
expect(projection.unclassified_components).toEqual([]);
expect(projection.packaging_model).toBe("unknown");
expect(projection.limitations).toContain(
"App Pack child packages are listed by inventory path only; their contents are not recursively inventoried by this projection.",
);
});
});
describe("HarmonyOS packaging boundaries", () => {
it("keeps a nested .app ZIP member inside an IPA out of the App Pack classification", async () => {
const nested = await writeApplicationZip(
"rea-harmony-nested-",
"Nested.app",
[{ path: "inner.txt", content: "not an app pack" }],
);
const path = await writeApplicationZip("rea-harmony-ipa-", "Fixture.ipa", [
{ path: "Payload/App.app/Info.plist", content: "plist" },
{
path: "Payload/Nested.app",
content: new Uint8Array(await readFile(nested)),
},
]);
const inventory = await inventoryApplicationPackage(path);
expect(fileIdentity(inventory.subject).format).toBe("ipa");
const occurrences = (
inventory.normalized_result as {
occurrences: Array<{
logical_path: string;
artifact_format: string;
}>;
}
).occurrences;
const nestedOccurrence = occurrences.find(
({ logical_path }) => logical_path === "Payload/Nested.app",
);
expect(nestedOccurrence?.artifact_format).toBe("zip");
});
it("claims the FA model only from config.json", async () => {
const path = await writeApplicationZip("rea-harmony-fa-", "Legacy.hap", [
{ path: "config.json", content: '{"app":{}}' },
{ path: "assets/js/default.js", content: "legacy();" },
{ path: "assets/entry/resources.index", content: "resource index" },
{
path: "assets/entry/resources/base/element/strings.json",
content: "{}",
},
{ path: "assets/feature/resources/rawfile/icon.png", content: "image" },
]);
const inventory = await inventoryApplicationPackage(path);
const result = projectHarmonyApplicationEvidence({
inventory_evidence: [inventory],
});
const projection = harmonyApplicationProjectionResultSchema.parse(
requireSuccessfulProjection(result).normalized_result,
);
expect(projection.packaging_model).toBe("fa");
expect(projection.runtime_families).toEqual(["javascript"]);
expect(projection.components.resources.map(({ path }) => path)).toEqual([
"assets/entry/resources.index",
"assets/entry/resources/base/element/strings.json",
"assets/feature/resources/rawfile/icon.png",
]);
});
it("does not classify a rawfile named module.json as a manifest", async () => {
const path = await writeApplicationZip(
"rea-harmony-rawfile-module-manifest-",
"Legacy.hap",
[
{ path: "config.json", content: '{"app":{}}' },
{
path: "assets/entry/resources/rawfile/module.json",
content: '{"note":"ordinary raw resource"}',
},
],
);
const inventory = await inventoryApplicationPackage(path);
const result = projectHarmonyApplicationEvidence({
inventory_evidence: [inventory],
});
const projection = harmonyApplicationProjectionResultSchema.parse(
requireSuccessfulProjection(result).normalized_result,
);
expect(projection.packaging_model).toBe("fa");
expect(projection.components.manifests.map(({ path }) => path)).toEqual([
"config.json",
]);
expect(projection.components.resources.map(({ path }) => path)).toEqual([
"assets/entry/resources/rawfile/module.json",
]);
});
it("rejects non-HarmonyOS inventory Evidence", async () => {
const inventory = await createNonApplicationZipInventory(
"rea-harmony-invalid-",
);
expect(
projectHarmonyApplicationEvidence({ inventory_evidence: [inventory] }),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
});
it("keeps HTTP Archive .har files out of the HarmonyOS classification", async () => {
const root = await createTestTempDirectory("rea-harmony-http-har-");
const path = join(root, "capture.har");
await writeFile(
path,
JSON.stringify({ log: { version: "1.2", creator: {}, entries: [] } }),
);
const result = await runProviderAnalysis(
path,
"inventory_artifact",
{},
).then(projectCliAnalysisResult);
expect(result).toMatchObject({
error: "Analysis failed",
code: "target_unavailable",
});
});
});
describe("HarmonyOS partial inventory classification", () => {
it("does not claim complete classification from a missing inventory occurrence", async () => {
const path = await writeApplicationZip(
"rea-harmony-partial-",
"Fixture.hap",
[
{ path: "module.json", content: "{}" },
{ path: ".pages.info", content: "page metadata" },
],
);
const inventory = await inventoryApplicationPackage(path);
const result = artifactInventoryResultSchema.parse(
inventory.normalized_result,
);
const partial = createEvidence(
{
path: fileSubjectDisplay(inventory.subject).local_path,
sha256: fileIdentity(inventory.subject).sha256,
format: fileIdentity(inventory.subject).format,
},
inventory.provider,
{
operation: inventory.operation,
parameters: inventory.parameters,
result: {
...result,
occurrences: result.occurrences.filter(
({ logical_path }) => logical_path !== ".pages.info",
),
},
confidence: "derived",
authority: inventory.authority,
},
);
const projection = requireDeterministicProjection(
projectHarmonyApplicationEvidence,
partial,
harmonyApplicationProjectionResultSchema,
);
expect(projection.unclassified_components).toEqual([]);
// Coverage is the structured fact a partial inventory reports, and the two
// independent causes of a partial projection stay empty, so `partial` is
// attributable to the missing occurrence alone. The prose limitation that
// accompanies it is explanatory wording, so it stays in review rather than
// in a substring assertion.
expect(projection.coverage).toEqual({
status: "partial",
inventory_complete: false,
});
expect(projection.unavailable_components).toEqual([]);
expect(projection.bridge_candidate_coverage).toEqual({
status: "complete",
total_candidates: 0,
emitted_candidates: 0,
omitted_candidates: 0,
});
const tampered = {
...partial,
normalized_result: inventory.normalized_result,
};
expect(
projectHarmonyApplicationEvidence({ inventory_evidence: [tampered] }),
).toMatchObject({
ok: false,
error: { _tag: "EvidenceIntegrityError" },
});
});
});
describe("HarmonyOS inventory coverage", () => {
it("retains complete traversal and case-collision limits in the application projection", async () => {
const path = await writeApplicationZip(
"rea-harmony-case-collision-",
"Fixture.hap",
[
{ path: "module.json", content: '{"module":{}}' },
{ path: "MODULE.JSON", content: '{"module":{}}' },
],
);
const inventory = await inventoryApplicationPackage(path);
expect(inventory.normalized_result).toMatchObject({
coverage: { scope: "container-entries", status: "complete" },
});
const projection = requireDeterministicProjection(
projectHarmonyApplicationEvidence,
inventory,
harmonyApplicationProjectionResultSchema,
);
expect(projection.coverage).toEqual({
status: "complete-within-inventory",
inventory_complete: true,
});
expect(projection.limitations.join(" ")).toContain(
"case-insensitive destination",
);
});
it.each(ZIP_PACKAGE_FORMATS)(
"retains archive identity and ZIP coverage for %s",
async (format) => {
const suffix = format === "app-pack" ? "app" : format;
const path = await writeApplicationZip(
"rea-package-family-",
`Fixture.${suffix}`,
[{ path: "module.json", content: "{}" }],
);
const target = await parseBinaryTarget(path);
if (!target.ok) throw target.error;
expect(target.value).toMatchObject({ kind: "archive", format });
const evidence = await inventoryApplicationPackage(path);
const inventory = artifactInventoryResultSchema.parse(
evidence.normalized_result,
);
expect(
inventory.occurrences.find(({ logical_path }) => logical_path === "."),
).toMatchObject({
artifact_kind: "container",
artifact_format: format,
});
expect(inventory.limitations).toContain(ZIP_NON_ENTRY_LIMITATION);
},
);
it("preserves unavailable encrypted component paths and qualifies absence", async () => {
const root = await createTestTempDirectory("rea-harmony-encrypted-");
const path = join(root, "Locked.hap");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("module.json", new TextReader("{}"));
await writer.add("ets/modules.abc", new TextReader("opaque bytecode"), {
password: "fixture-only",
});
await writer.add("pkgContextInfo.json", new TextReader("{}"), {
password: "fixture-only",
});
await writeFile(path, await writer.close());
const evidence = await inventoryApplicationPackage(path);
const projection = requireDeterministicProjection(
projectHarmonyApplicationEvidence,
evidence,
harmonyApplicationProjectionResultSchema,
);
expect(projection.components.bytecode).toEqual([]);
expect(projection.unclassified_components).toEqual([]);
expect(projection.unavailable_components).toEqual([
expect.objectContaining({
path: "ets/modules.abc",
artifact_id: null,
sha256: null,
encrypted: true,
}),
expect.objectContaining({
path: "pkgContextInfo.json",
artifact_id: null,
sha256: null,
encrypted: true,
}),
]);
expect(projection.coverage).toEqual({
status: "partial",
inventory_complete: true,
});
expect(projection.limitations).toContainEqual(
expect.stringContaining("component and runtime absence is unknown"),
);
});
});
describe("HarmonyOS manifest path rules", () => {
it("claims stage and FA models only from the exact manifest filenames", async () => {
// HAP/HSP/App Pack members are ZIP names. OpenHarmony's stage, FA, and
// app-pack manifests are module.json, config.json, and pack.info.
const path = await writeApplicationZip(
"rea-harmony-manifest-case-",
"Fixture.hap",
[
{ path: "MODULE.JSON", content: "{}" },
{ path: "CONFIG.JSON", content: "{}" },
{ path: "PACK.INFO", content: "{}" },
],
);
const projection = requireDeterministicProjection(
projectHarmonyApplicationEvidence,
await inventoryApplicationPackage(path),
harmonyApplicationProjectionResultSchema,
);
expect(projection.packaging_model).toBe("unknown");
expect(projection.components.manifests).toEqual([]);
// Exact-case manifest names only, so these members belong to no manifest
// category and are disclosed as unclassified rather than silently dropped.
expect(
projection.unclassified_components.map(({ path }) => path).sort(),
).toEqual(["CONFIG.JSON", "MODULE.JSON", "PACK.INFO"]);
});
it.each([
{ paths: ["a/module.json", "z/config.json"] },
{ paths: ["a/config.json", "z/module.json"] },
])("keeps Stage precedence for $paths", async ({ paths }) => {
const path = await writeApplicationZip(
"rea-harmony-mixed-model-",
"Both.hap",
paths.map((path) => ({ path, content: "{}" })),
);
const projection = requireDeterministicProjection(
projectHarmonyApplicationEvidence,
await inventoryApplicationPackage(path),
harmonyApplicationProjectionResultSchema,
);
expect(projection.packaging_model).toBe("stage");
expect(
projection.components.manifests.map(({ path }) => path).sort(),
).toEqual(paths.toSorted());
});
it.each([
{ name: "module.json", model: "stage" },
{ name: "config.json", model: "fa" },
{ name: "MODULE.JSON", model: "unknown" },
])("retains the path hint for unavailable $name", async ({ name, model }) => {
const root = await createTestTempDirectory("rea-harmony-locked-manifest-");
const path = join(root, "Locked.hap");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add(name, new TextReader("{}"), { password: "fixture-only" });
await writeFile(path, await writer.close());
const projection = requireDeterministicProjection(
projectHarmonyApplicationEvidence,
await inventoryApplicationPackage(path),
harmonyApplicationProjectionResultSchema,
);
expect(projection.packaging_model).toBe(model);
expect(projection.components.manifests).toEqual([]);
expect(projection.unavailable_components).toEqual([
expect.objectContaining({
path: name,
artifact_id: null,
sha256: null,
encrypted: true,
}),
]);
expect(projection.coverage).toEqual({
status: "partial",
inventory_complete: true,
});
});
});