Compare commits

..
Author SHA1 Message Date
morluto a74b11e99a chore: sync branch with latest main 2026-10-08 23:52:20 +08:00
morluto eb85e932ac docs(artifacts): clarify extraction materialization evidence 2026-10-08 23:48:06 +08:00
morluto 35a955ac15 fix(artifacts): correlate unpacked integrity with materialized companions 2026-10-08 23:46:05 +08:00
morluto 761a898926 chore: merge main and reconcile CI projections 2026-10-08 23:45:07 +08:00
morluto 3334db2bde fix(ci): restore generated projections in test shards 2026-10-08 23:31:52 +08:00
morluto 97359fe189 chore: synchronize integrity policy branch with latest main guidance 2026-10-08 23:16:56 +08:00
morluto 09a0c363d9 fix(artifacts): preserve integrity evidence across workflows and integrate main 2026-10-08 23:16:16 +08:00
ac392da332 fix(artifacts): keep integrity policy and extraction claims aligned (#1083)
* fix(artifacts): keep integrity policy and extraction claims aligned

rea analyze routed a JavaScript application without the integrity policy,
so the remediation flag it recommends was rejected on that command. The
routed command now accepts --integrity-policy and forwards it.

Extraction copied every inventory contradiction into the result and said
those files were written. Only materialized occurrences stay in that list;
nested contradictions are named as unwritten.

* test(artifacts): type the nested extraction fixture as a directory path

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2026-10-08 22:41:35 +08:00
Kaoru0822 467f68412e Merge remote-tracking branch 'origin/main' into feat/artifact-integrity-policy 2026-10-07 14:50:36 +00:00
Kaoru0822andClaude Opus 5.5 22f4dc101a Merge origin/main into feat/artifact-integrity-policy
Keep main's skill metadata version (27) and regenerate the package, tool
catalog and product metadata for the merged tree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 14:18:28 +00:00
Kaoru0822andClaude Opus 5.5 be011ea3ba Merge origin/main into feat/artifact-integrity-policy
Keep both new MCP extraction tests, use main's relocated Apple domain
imports, and regenerate the catalog metadata.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:41:30 +00:00
morluto 40a33d3d3b chore: merge main and regenerate combined catalog metadata 2026-10-07 18:44:31 +08:00
morluto 464115f2ec chore: merge main and retain artifact integrity evidence 2026-10-07 18:02:05 +08:00
morluto 883db73b3f chore: merge main and resolve PR #902 conflicts 2026-10-07 17:28:56 +08:00
Kaoru0822andClaude Opus 5.5 5aafaa00ec fix(artifacts): carry recorded integrity contradictions into application workflows
A recorded contradiction appeared only in the analyze_javascript_application
response. Version and source comparisons, feature traces, and export-shape
comparisons read the application graph, which still claimed complete
coverage, so they could report complete-within-inputs results over
untrusted bytes. The graph is now partial when contradictions were
recorded, and its limitations, inherited by the result and the semantic
graph, name every contradicted path.

The mismatch remediation names both spellings: integrity_policy in MCP
and --integrity-policy on the CLI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 08:50:41 +00:00
Kaoru0822 92b373e660 Merge remote-tracking branch 'origin/main' into feat/artifact-integrity-policy
# Conflicts:
#	docs/product-catalog.json
#	docs/verification/managed-conformance-manifest.json
#	skills/reverse-engineer-anything/SKILL.md
#	src/generatedMcpToolCatalog.ts
2026-10-07 08:37:04 +00:00
Kaoru0822andClaude Opus 5.5 69af884666 feat(artifacts): let extraction and JavaScript analysis record integrity mismatches
macOS code signing rewrites unpacked native modules after electron-builder
records their ASAR integrity, so the declared and observed hashes of
those .node files differ in most signed Electron apps. Claude, ChatGPT,
Notion, Obsidian, and Tabby all failed inspect_artifact,
extract_artifact, and analyze_javascript_application by default. Only
inspect_artifact offered integrity_policy, so extraction and JavaScript
analysis of these apps was impossible.

extract_artifact and analyze_javascript_application now accept the same
integrity_policy (default fail). With record-and-continue, extraction
writes the observed bytes, and JavaScript analysis reads contradicted
files as observed. Contradicted nested archives stay unexpanded. Both
results return the recorded integrity_contradictions and a limitation.
The mismatch remediation now names this option instead of only advising a
fresh copy, which cannot help for a signed installation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 08:28:44 +00:00
54 changed files with 738 additions and 3791 deletions
-1
View File
@@ -317,7 +317,6 @@ jobs:
- run: npm run verify:keyed-archive
- run: npm run verify:asset-catalog
- run: npm run verify:macos-bundle
- run: npm run verify:code-signature
- name: Native installer and compiled NIB hierarchy regressions
run: npm run test:focused -- tests/boundary/filesystem/installScript.test.ts tests/boundary/filesystem/nibNativeHierarchy.test.ts tests/boundary/filesystem/interfaceBuilderBundle.test.ts
- name: Real binary metadata and Interface Builder integration
+12 -4
View File
@@ -276,11 +276,19 @@ and returns its result and Evidence inline.
## Integrity record-and-continue
Artifact integrity fails closed by default. A request can explicitly select
Artifact integrity fails closed by default. `inspect_artifact`,
`extract_artifact`, and `analyze_javascript_application` accept
`integrity_policy=record-and-continue` when the investigation needs verified
siblings to continue after a mismatch.
siblings to continue after a mismatch. A common expected mismatch is an
unpacked native module that macOS code signing rewrote after the ASAR header
recorded its integrity.
Contradictory bytes are quarantined from nested expansion and recorded with
declared and observed hashes, trust, provenance, path, and unpacked state.
Verified siblings continue. Comparisons classify the result as a contradiction
and reconstruction cannot treat it as unchanged.
Verified siblings continue. Extraction writes the observed bytes and returns the
contradictions with its result; JavaScript analysis reads contradicted files as
observed and lists them in `integrity_contradictions`. Comparisons classify the
result as a contradiction and reconstruction cannot treat it as unchanged.
Application comparisons and feature traces retain the source integrity warnings
and report incomplete coverage. Extraction retains nested contradiction records
without claiming that the nested members were materialized separately.
-14
View File
@@ -98,20 +98,6 @@ an XML graph golden. `verify:asset-catalog` compiles source-owned colors with
`actool`, invokes real `assetutil`, then checks CLI/MCP results, exact catalog
digest, every raw metadata field, pagination and malformed input rejection.
Neither artifact workflow requires Hopper or launches it. Both run in macOS CI.
`verify:code-signature` needs only macOS with Command Line Tools. It re-signs
copies of a clang-built fixture with real `codesign`: ad hoc, hardened
runtime, hardened runtime with relaxing entitlements, and `library,restrict`
flags. It checks that `inspect-signature` decodes those flags and derives the
expected security facets. It also checks a platform binary, which must report a
platform identifier and pass the `anchor apple` origin check, and bundles with an added unsealed file, at the top level
and inside a nested XPC service, which must fail deep strict verification. CLI and stdio MCP results must match.
The default lane explicitly reports real stapled-ticket coverage as unverified:
its source-built ad hoc fixtures cannot receive genuine Apple notarization tickets.
To verify ticket producer output through CLI and MCP, supply an existing stapled app:
`npm run verify:code-signature -- --stapled-app "/Applications/Firefox.app"`.
This optional subcase preflights `xcrun stapler`, validates the selected app with
Apple's tool, and checks that both REA surfaces return the same ticket digest and
`present` framing observation. It does not install an app or submit anything for notarization.
`verify:macos-bundle` needs only macOS with Command Line Tools. It compiles a
source-owned app with `clang`: a versioned framework, XPC services, an app
extension, a login item, a privileged helper, launchd plists, and a helper tool,
-1
View File
@@ -142,7 +142,6 @@
"verify:apple-dispatch": "npm run build:cached && node scripts/verify/apple/dispatch.mjs",
"verify:native-ui": "npm run build:cached && node scripts/verify-native-ui.mjs",
"verify:keyed-archive": "npm run build:cached && node scripts/verify/apple/keyed-archive.mjs",
"verify:code-signature": "npm run build:cached && node scripts/verify/apple/code-signature.mjs",
"verify:macos-bundle": "npm run build:cached && node scripts/verify/apple/macos-bundle.mjs",
"verify:ghidra": "npm run build:cached && node scripts/verify-real-ghidra.mjs",
"verify:ida": "npm run build:cached && node scripts/verify-real-ida.mjs",
-291
View File
@@ -1,291 +0,0 @@
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import {
copyFile,
lstat,
mkdir,
mkdtemp,
realpath,
rm,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
import {
artifactCli,
artifactMcpResult,
withArtifactMcp,
} from "../../lib/artifact-e2e.mjs";
import {
buildMacosBundleFixture,
preflightMacosBundleFixture,
} from "../../fixtures/apple/macos-bundle.mjs";
const exec = promisify(execFile);
const args = process.argv.slice(2);
if (args.length !== 0 && (args.length !== 2 || args[0] !== "--stapled-app"))
throw new Error("Usage: verify:code-signature [--stapled-app PATH]");
const stapledApp = args[1];
if (stapledApp !== undefined) {
try {
await exec("/usr/bin/xcrun", ["--find", "stapler"]);
} catch (cause) {
throw new Error("Real stapled-ticket verification requires xcrun stapler", {
cause,
});
}
}
await preflightMacosBundleFixture();
const root = await mkdtemp(join(tmpdir(), "rea-code-signature-"));
const facets = (signature) =>
Object.fromEntries(
signature.security_facets.map(({ facet, state }) => [facet, state]),
);
/** Re-sign a copy of one fixture executable ad hoc with the given options. */
const signedCopy = async (source, name, options) => {
const path = join(root, name);
await copyFile(source, path);
await exec("/usr/bin/xcrun", [
"codesign",
"--force",
"--sign",
"-",
...options,
path,
]);
return path;
};
const ENTITLEMENTS = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>com.apple.security.cs.disable-library-validation</key><true/>
<key>com.apple.security.cs.allow-dyld-environment-variables</key><true/>
<key>com.apple.security.get-task-allow</key><true/>
<key>com.apple.security.cs.allow-jit</key><true/>
</dict></plist>
`;
try {
const { app } = await buildMacosBundleFixture(root);
let realTicket = {
status: "unverified",
reason:
"No known stapled app supplied; use --stapled-app PATH to exercise producer output.",
};
if (stapledApp !== undefined) {
const appPath = await realpath(stapledApp);
const oracle = await exec("/usr/bin/xcrun", [
"stapler",
"validate",
appPath,
]);
const observed = await artifactCli("inspect-signature", appPath);
assert.equal(
observed.stapled_ticket.status,
"present",
JSON.stringify(observed.stapled_ticket),
);
assert.equal(observed.stapled_ticket.reason, null);
assert.match(observed.stapled_ticket.sha256, /^[a-f0-9]{64}$/u);
await withArtifactMcp(appPath, async (client) => {
const viaMcp = await artifactMcpResult(client, "inspect_signature");
assert.deepEqual(viaMcp.stapled_ticket, observed.stapled_ticket);
});
realTicket = {
status: "verified",
selected_app: stapledApp,
ticket_sha256: observed.stapled_ticket.sha256,
size: observed.stapled_ticket.size,
oracle: "xcrun stapler validate",
stdout: oracle.stdout,
stderr: oracle.stderr,
};
}
const plain = await artifactCli("inspect-signature", app);
assert.deepEqual(plain.code_directory.flags.names, ["adhoc"]);
assert.equal(plain.verification.status, "valid");
// The opened bundle is reported by its canonical path.
assert.equal(plain.verification.path, await realpath(app));
assert.equal(plain.stapled_ticket.status, "absent");
assert.equal(plain.sealed_resources.status, "sealed");
assert.deepEqual(facets(plain), {
"library-validation": "not-enforced",
"dyld-environment-variables": "honored",
"debugger-attach": "allowed",
"executable-memory": "unrestricted",
"app-sandbox": "not-sandboxed",
});
// Deep verification reports the fixture's real nested code, all on disk.
assert.ok(plain.verification.validated_nested_code.length > 0);
const checkNestedProgress = async (signature) => {
for (const path of signature.verification.validated_nested_code) {
try {
await lstat(path);
} catch {
assert.ok(
signature.limitations.some((limitation) =>
limitation.includes(JSON.stringify(path)),
),
`Unconfirmed progress pathname must retain its limitation: ${path}`,
);
}
}
};
await checkNestedProgress(plain);
await withArtifactMcp(app, async (client) => {
const viaMcp = await artifactMcpResult(client, "inspect_signature");
assert.equal(viaMcp.verification.status, plain.verification.status);
assert.equal(viaMcp.verification.path, plain.verification.path);
await checkNestedProgress(viaMcp);
// Separate live codesign runs can interleave progress records differently.
// Compare the artifact's signature posture; check each capture independently.
const semantic = ({ provenance, verification, limitations, ...posture }) =>
posture;
assert.deepEqual(semantic(viaMcp), semantic(plain));
});
const tool = join(app, "Contents/Helpers/rea-tool");
const hardened = await artifactCli(
"inspect-signature",
await signedCopy(tool, "hardened", ["--options", "runtime"]),
);
assert.deepEqual(hardened.code_directory.flags.names, ["adhoc", "runtime"]);
assert.equal(hardened.stapled_ticket.status, "not-applicable");
assert.deepEqual(facets(hardened), {
"library-validation": "enforced",
"dyld-environment-variables": "ignored",
"debugger-attach": "blocked",
"executable-memory": "restricted",
"app-sandbox": "not-sandboxed",
});
const entitlements = join(root, "relaxed.entitlements");
await writeFile(entitlements, ENTITLEMENTS);
const relaxed = await artifactCli(
"inspect-signature",
await signedCopy(tool, "relaxed", [
"--options",
"runtime",
"--entitlements",
entitlements,
]),
);
assert.deepEqual(facets(relaxed), {
"library-validation": "disabled",
"dyld-environment-variables": "honored",
"debugger-attach": "allowed",
"executable-memory": "jit-allowed",
"app-sandbox": "not-sandboxed",
});
const flagged = await artifactCli(
"inspect-signature",
await signedCopy(tool, "flagged", ["--options", "library,restrict"]),
);
assert.deepEqual(flagged.code_directory.flags.names, [
"adhoc",
"restrict",
"library-validation",
]);
assert.equal(facets(flagged)["library-validation"], "enforced");
assert.equal(facets(flagged)["dyld-environment-variables"], "ignored");
const platform = await artifactCli("inspect-signature", "/usr/bin/true");
assert.notEqual(platform.code_directory.platform_identifier, null);
assert.equal(platform.verification.status, "valid");
assert.equal(facets(platform)["library-validation"], "enforced");
// The platform rules rest on a real `anchor apple` requirement check.
assert.ok(
platform.provenance.some(({ command }) =>
command.includes("-R=anchor apple"),
),
);
// Negative fixtures contain only the code needed for each rejection. A large
// nested-code graph can interleave codesign progress, making that capture
// inconclusive independently of the invalidity these checks exercise.
const minimalApp = async (name, includeNested) => {
const bundle = join(root, `${name}.app`);
const contents = join(bundle, "Contents");
await mkdir(join(contents, "MacOS"), { recursive: true });
await copyFile(tool, join(contents, "MacOS", "Fixture"));
await writeFile(
join(contents, "Info.plist"),
`<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0"><dict><key>CFBundleExecutable</key><string>Fixture</string>
<key>CFBundleIdentifier</key><string>com.example.rea.signature</string>
<key>CFBundlePackageType</key><string>APPL</string></dict></plist>`,
);
if (includeNested) {
await mkdir(join(contents, "XPCServices"));
await exec("/usr/bin/ditto", [
join(app, "Contents/XPCServices/Svc.xpc"),
join(contents, "XPCServices/Svc.xpc"),
]);
}
await exec("/usr/bin/xcrun", [
"codesign",
"--force",
"--deep",
"--sign",
"-",
bundle,
]);
assert.equal(
(await artifactCli("inspect-signature", bundle)).verification.status,
"valid",
);
return bundle;
};
const nested = await minimalApp("Nested", true);
await writeFile(
join(nested, "Contents/XPCServices/Svc.xpc/Contents/added.txt"),
"unsealed",
);
const nestedTamper = await artifactCli("inspect-signature", nested);
assert.equal(nestedTamper.verification.status, "invalid");
assert.ok(
nestedTamper.verification.diagnostics.some((line) =>
line.includes("Svc.xpc"),
),
JSON.stringify(nestedTamper.verification),
);
const mainTamper = await minimalApp("Tampered", false);
await mkdir(join(mainTamper, "Contents/Resources"));
await writeFile(join(mainTamper, "Contents/Resources/added.txt"), "unsealed");
const tampered = await artifactCli("inspect-signature", mainTamper);
assert.equal(tampered.verification.status, "invalid");
assert.ok(
tampered.verification.diagnostics.some((line) => line.includes("added")),
JSON.stringify(tampered.verification),
);
process.stdout.write(
`${JSON.stringify({
ok: true,
mocked: false,
cli: true,
stdio_mcp: true,
variants: [
"adhoc",
"runtime",
"runtime+entitlements",
"library,restrict",
],
platform_identifier: platform.code_directory.platform_identifier,
tampered_verification: tampered.verification.status,
nested_tamper_verification: nestedTamper.verification.status,
real_stapled_ticket: realTicket,
})}\n`,
);
} finally {
await rm(root, { recursive: true, force: true });
}
@@ -91,12 +91,6 @@ ASAR, or DMG inputs when the artifact graph and findings help answer the
question. It returns the complete artifact graph inline. Cite graph manifest
IDs when using them.
`inspect_signature` decodes CodeDirectory flags, runs local strict
verification, reports a stapled notarization ticket, and derives security
facets: library validation, `DYLD_*` handling, debugger attach, executable
memory, and sandbox. Cite each facet's `evidence`; system policy such as SIP and
AMFI is not evaluated.
For an IPA or a macOS `.app`, ZIP, or DMG, pass the inventory Evidence to
`project_apple_application_graph`. It reports application roots and nested
bundles by path convention: app extensions, XPC services, frameworks, login
@@ -51,4 +51,5 @@ const parameters = (
input: AnalyzeJavaScriptApplicationInput,
): EvidenceObservation["parameters"] => ({
format: input.format,
integrity_policy: input.integrity_policy,
});
@@ -1,12 +1,18 @@
import { writeFile } from "node:fs/promises";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createPackageWithOptions } from "@electron/asar";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import { analyzeJavaScriptApplication } from "./JavaScriptApplicationService.js";
import {
compareApplicationVersionsEvidence,
compareJavaScriptExportShapesEvidence,
traceApplicationFeatureEvidence,
} from "./JavaScriptApplicationWorkflowService.js";
describe("JavaScript application failure diagnostics", () => {
it("identifies the rejected result field in caller-visible diagnostics", async () => {
@@ -155,3 +161,107 @@ describe("JavaScript application failure diagnostics", () => {
},
);
});
const CONTRADICTION_LIMITATION =
"Observed bytes of 1 artifact file(s) contradict declared integrity and are untrusted: addon.node.";
describe("JavaScript application artifact integrity", () => {
it("analyzes a signed-after-packaging native module only when the mismatch is recorded", async () => {
const root = await createTestTempDirectory("rea-js-integrity-");
const source = join(root, "source");
await mkdir(source);
await writeFile(
join(source, "package.json"),
'{"name":"signed","main":"main.js"}',
);
await writeFile(
join(source, "main.js"),
"require('./addon.node'); export function value() { return {status: 'ready'}; }\n",
);
await writeFile(join(source, "addon.node"), "packed native bytes");
const archive = join(root, "app.asar");
await createPackageWithOptions(source, archive, { unpack: "*.node" });
// macOS code signing rewrites unpacked binaries after the archive header
// has recorded their integrity.
await writeFile(
join(`${archive}.unpacked`, "addon.node"),
"signed native bytes",
);
const strict = await analyzeJavaScriptApplication({ input_path: archive });
expect(strict.ok).toBe(false);
if (strict.ok) throw new Error("Expected an integrity failure");
expect(projectAnalysisError(strict.error)).toMatchObject({
code: "artifact_integrity_mismatch",
details: { logical_path: "addon.node", unpacked: true },
});
const recorded = await analyzeJavaScriptApplication({
input_path: archive,
integrity_policy: "record-and-continue",
});
expect(recorded.ok).toBe(true);
if (!recorded.ok) throw new Error("Expected recorded analysis");
expect(recorded.value.parameters).toEqual({
format: "auto",
integrity_policy: "record-and-continue",
});
expect(recorded.value.normalized_result).toMatchObject({
format: "asar",
integrity_contradictions: [
{
logical_path: "addon.node",
unpacked: true,
trust: "observed-untrusted",
},
],
graph: { coverage: { status: "partial" } },
limitations: expect.arrayContaining([CONTRADICTION_LIMITATION]),
semantic_graph: {
limitations: expect.arrayContaining([CONTRADICTION_LIMITATION]),
},
});
// Workflows built on the recorded graph inherit its partial coverage.
const clean = await analyzeJavaScriptApplication({
input_path: source,
format: "directory",
});
if (!clean.ok) throw new Error("Expected clean analysis");
const comparison = compareApplicationVersionsEvidence({
left: clean.value,
right: recorded.value,
});
expect(comparison.ok).toBe(true);
if (!comparison.ok) throw new Error("Expected comparison");
expect(comparison.value.normalized_result).toMatchObject({
coverage: { status: "partial", right_graph_status: "partial" },
limitations: expect.arrayContaining([CONTRADICTION_LIMITATION]),
});
const shapes = compareJavaScriptExportShapesEvidence({
left: clean.value,
right: recorded.value,
left_module_path: "main.js",
left_export_name: "value",
right_module_path: "main.js",
right_export_name: "value",
});
expect(shapes.ok).toBe(true);
if (!shapes.ok) throw shapes.error;
expect(shapes.value.normalized_result).toMatchObject({
coverage: { status: "partial" },
limitations: expect.arrayContaining([CONTRADICTION_LIMITATION]),
});
const trace = traceApplicationFeatureEvidence({
application: recorded.value,
seed: { kind: "string", value: "nonexistent-feature" },
direction: "outgoing",
});
expect(trace.ok).toBe(true);
if (!trace.ok) throw trace.error;
expect(trace.value.normalized_result).toMatchObject({
graph: null,
limitations: expect.arrayContaining([CONTRADICTION_LIMITATION]),
});
});
});
@@ -55,6 +55,7 @@ export const analyzeJavaScriptApplicationValidated = async (
{
input_path: input.input_path,
format: input.format,
integrity_policy: input.integrity_policy,
},
options.signal,
options.progress,
@@ -92,6 +92,7 @@ const graphCoverage = (context: JavaScriptArtifactGraphContext) => {
javascript !== null && javascript.parse_status === "partial",
);
const unknownGap =
context.snapshot.integrity_contradictions.length > 0 ||
context.analysis.parse_failures > 0 ||
context.fileSet.invalid_utf8_files > 0 ||
sourceMapPolicyGap ||
@@ -103,6 +104,20 @@ const graphCoverage = (context: JavaScriptArtifactGraphContext) => {
return completeApplicationCoverage();
};
/**
* Disclose recorded integrity contradictions wherever the application graph
* is consumed; the graph is also partial, so comparisons and traces built on
* it do not claim completeness.
*/
export const integrityContradictionLimitations = (
snapshot: Pick<ArtifactInventorySnapshot, "integrity_contradictions">,
): string[] =>
snapshot.integrity_contradictions.length === 0
? []
: [
`Observed bytes of ${String(snapshot.integrity_contradictions.length)} artifact file(s) contradict declared integrity and are untrusted: ${snapshot.integrity_contradictions.map(({ logical_path: path }) => path).join(", ")}.`,
];
const graphLimitations = (
context: JavaScriptArtifactGraphContext,
coverage: "complete" | "partial" | "unknown" | "unavailable",
@@ -124,6 +139,7 @@ const graphLimitations = (
);
return [
...context.analysis.limitations,
...integrityContradictionLimitations(context.snapshot),
"CommonJS and ESM binding relationships were recovered from inert syntax and resolved only within the inventoried artifact container.",
"Webpack/Rspack factories were recovered from AST literals; REA did not invoke push handlers or bundle bootstrap code.",
"Static imports, entrypoints, workers, endpoints, and storage relationships do not prove runtime execution.",
@@ -5,9 +5,13 @@ import { createJavaScriptArtifactReader as createReader } from "../../artifacts/
import type { JavaScriptApplicationGraph } from "../../domain/javascript/javascriptApplicationGraph.js";
import type { JavaScriptSemanticGraph } from "../../domain/javascript/javascriptSemanticGraph.js";
import type { ElectronBoundarySummary } from "../../domain/javascript/javascriptApplicationAnalysis.js";
import type { IntegrityContradiction } from "../../domain/artifactGraph.js";
import { analyzeAndProjectJavaScriptArtifactFiles } from "./JavaScriptArtifactAnalysis.js";
import { readJavaScriptArtifactFiles } from "../../artifacts/javascript/JavaScriptArtifactFiles.js";
import { buildJavaScriptArtifactGraph } from "./JavaScriptArtifactGraphBuilder.js";
import {
buildJavaScriptArtifactGraph,
integrityContradictionLimitations,
} from "./JavaScriptArtifactGraphBuilder.js";
import {
javascriptArtifactReconstructionInputSchema,
type JavaScriptArtifactReconstructionInput,
@@ -27,6 +31,7 @@ export interface JavaScriptArtifactReconstructionResult {
readonly graph: JavaScriptApplicationGraph;
readonly semantic_graph: JavaScriptSemanticGraph;
readonly electron_summary: ElectronBoundarySummary;
readonly integrity_contradictions: readonly IntegrityContradiction[];
readonly statistics: {
readonly relevant_files: number;
readonly nested_asar_containers: number;
@@ -55,7 +60,10 @@ export const reconstructJavaScriptArtifact = async (
abortIfNeeded(signal);
const path = await realpath(input.input_path);
const format = await resolveFormat(path, input);
const snapshot = await scanCanonicalArtifactInventory(path, { signal });
const snapshot = await scanCanonicalArtifactInventory(path, {
signal,
integrity: { mode: input.integrity_policy },
});
if (snapshot.manifest.root_format !== format)
throw new ArtifactReaderFailure(
"format",
@@ -101,6 +109,7 @@ export const reconstructJavaScriptArtifact = async (
snapshot.manifest.root_sha256,
graph,
analysis,
integrityContradictionLimitations(snapshot),
);
return {
input_path: path,
@@ -111,6 +120,7 @@ export const reconstructJavaScriptArtifact = async (
graph,
semantic_graph: semanticGraph,
electron_summary: summarizeElectronBoundaries(analysis),
integrity_contradictions: snapshot.integrity_contradictions,
statistics: {
relevant_files: files.files.length,
nested_asar_containers: files.containers.length,
@@ -1,9 +1,12 @@
import { z } from "zod";
import { artifactIntegrityPolicySchema } from "../../domain/artifactGraph.js";
/** Local ASAR/directory reconstruction request. */
export const javascriptArtifactReconstructionInputSchema = z.strictObject({
input_path: z.string().min(1),
format: z.enum(["auto", "asar", "directory"]).default("auto"),
integrity_policy: artifactIntegrityPolicySchema,
});
/** Parsed local reconstruction request. */
@@ -59,6 +59,8 @@ interface BuilderInput {
"graph_id" | "nodes"
>;
readonly analysis: JavaScriptArtifactAnalysis;
/** Source facts the semantic graph inherits, such as integrity contradictions. */
readonly sourceLimitations?: readonly string[];
}
interface FileContext extends SemanticFlowProjectionContext {
@@ -111,13 +113,19 @@ export const buildJavaScriptSemanticGraph = ({
rootArtifactSha256,
applicationGraph,
analysis,
sourceLimitations = [],
}: BuilderInput): JavaScriptSemanticGraph => {
const projection = createJavaScriptSemanticGraphProjection();
for (const analyzed of analysis.files) {
if (analyzed.semantic !== null)
projection.projectFile(analyzed.file, analyzed.semantic.ir);
}
return projection.finish(rootArtifactSha256, applicationGraph, analysis);
return projection.finish(
rootArtifactSha256,
applicationGraph,
analysis,
sourceLimitations,
);
};
/** File-local semantic projection that does not retain consumed source IR. */
@@ -130,6 +138,7 @@ export interface JavaScriptSemanticGraphProjection {
rootArtifactSha256: string,
applicationGraph: BuilderInput["applicationGraph"],
analysis: Pick<JavaScriptArtifactAnalysis, "truncated_scopes">,
sourceLimitations?: readonly string[],
) => JavaScriptSemanticGraph;
}
@@ -163,7 +172,12 @@ export const createJavaScriptSemanticGraphProjection =
};
return {
projectFile: projectSource,
finish: (rootArtifactSha256, applicationGraph, analysis) => {
finish: (
rootArtifactSha256,
applicationGraph,
analysis,
sourceLimitations = [],
) => {
bindSemanticGraphApplicationNodes(state, applicationGraph);
if (state.roots.size === 0) addFallbackRoot(rootArtifactSha256, state);
const unknowns = [...state.unknowns.values()];
@@ -206,6 +220,7 @@ export const createJavaScriptSemanticGraphProjection =
})),
},
limitations: [
...sourceLimitations,
"The semantic graph contains static syntax observations and conservative relationship candidates; it does not claim runtime execution.",
"Local data flow does not claim control-flow-sensitive reaching definitions or arbitrary dynamic property resolution.",
"Promise ownership covers explicit unshadowed Promise construction, static factories, aggregation, chaining, and await syntax only.",
+3
View File
@@ -171,6 +171,9 @@ class ArtifactClient implements AnalysisClient {
inputPath: this.target.sourcePath ?? this.target.path,
inputFormat: this.target.format,
outputRoot: parsed.output_root,
integrity: resolveArtifactIntegrityPolicy({
mode: parsed.integrity_policy,
}),
},
options?.signal,
);
+58 -35
View File
@@ -21,15 +21,19 @@ import {
type ArtifactGraphManifest,
type ArtifactNode,
type ArtifactOccurrence,
type IntegrityContradiction,
} from "../../domain/artifactGraph.js";
import type { BinaryTarget } from "../../domain/binaryTarget.js";
import { scanArtifactInventory } from "../inventory/ArtifactInventory.js";
import type { ArtifactIntegrityPolicy } from "../inventory/types.js";
/** Local extraction input with the output root chosen by the adapter. */
export interface ArtifactExtractionInput {
readonly inputPath: string;
readonly inputFormat: BinaryTarget["format"];
readonly outputRoot: string;
/** Integrity mismatches fail unless the caller records and continues. */
readonly integrity?: ArtifactIntegrityPolicy;
}
/** Extract every regular inventory occurrence into an exclusively owned absent root. */
@@ -40,29 +44,25 @@ export const extractArtifact = async (
const sourcePath = await realpath(input.inputPath);
const snapshot = await scanArtifactInventory(sourcePath, {
signal,
integrity: input.integrity,
});
const selectedOccurrences = snapshot.occurrences.filter(
(occurrence) =>
(occurrence.entry_kind === "file" || occurrence.entry_kind === "slice") &&
occurrence.logical_path !== ".",
);
const selectedIds = new Set(
selectedOccurrences.map(({ occurrence_id: id }) => id),
const occurrences = new Map(
snapshot.occurrences.map((occurrence) => [
occurrence.occurrence_id,
occurrence,
]),
);
const occurrences = new Map<string, ArtifactOccurrence>();
const neededNodes = new Set<string>();
collectOccurrences(
snapshot.occurrences,
selectedIds,
occurrences,
neededNodes,
);
const nodes = new Map<string, ArtifactNode>();
collectNodes(snapshot.nodes, neededNodes, nodes);
const nodes = new Map(snapshot.nodes.map((node) => [node.artifact_id, node]));
const inventory: LoadedInventory = {
manifest: snapshot.manifest,
occurrences,
nodes,
integrityContradictions: snapshot.integrity_contradictions,
};
const selected = selectedOccurrences.map((occurrence) => {
if (
@@ -187,6 +187,39 @@ const createExtractionResult = (
selected: readonly SelectedOccurrence[],
extracted: readonly ExtractedOccurrence[],
): ArtifactExtractionResult => {
const materializedIds = new Set(
selected.map(({ occurrence }) => occurrence.occurrence_id),
);
const materializedPaths = new Map(
selected.map(({ occurrence }) => [occurrence.logical_path, occurrence]),
);
const wasMaterialized = (contradiction: IntegrityContradiction): boolean => {
if (materializedIds.has(contradiction.occurrence_id)) return true;
if (!contradiction.unpacked) return false;
// An unpacked member is read beside its enclosing ASAR, not from ASAR bytes.
const occurrence = inventory.occurrences.get(contradiction.occurrence_id);
let parentId = occurrence?.parent_occurrence_id;
while (parentId !== null && parentId !== undefined) {
const parent = inventory.occurrences.get(parentId);
if (parent === undefined) return false;
if (
parent.artifact_id !== null &&
inventory.nodes.get(parent.artifact_id)?.format === "asar"
) {
const companion = materializedPaths.get(
`${parent.logical_path}.unpacked${contradiction.logical_path.slice(parent.logical_path.length)}`,
);
return companion?.artifact_id === occurrence?.artifact_id;
}
parentId = parent.parent_occurrence_id;
}
return false;
};
const writtenContradictions =
inventory.integrityContradictions.filter(wasMaterialized);
const nestedContradictions = inventory.integrityContradictions.filter(
(contradiction) => !wasMaterialized(contradiction),
);
const extractionSemantic = {
source_manifest_id: inventory.manifest.manifest_id,
selected_occurrence_ids: selected
@@ -206,8 +239,19 @@ const createExtractionResult = (
containment_verified: true,
cleanup: { attempted: false, verified: true, residual_paths: [] },
provenance: [],
integrity_contradictions: inventory.integrityContradictions,
limitations: [
"All regular files in the active artifact were materialized; nested archive contents remain represented by their containing file.",
"All regular files in the active artifact were materialized. The artifacts list identifies written files; nested inventory observations may refer to additional logical paths.",
...(writtenContradictions.length === 0
? []
: [
`${String(writtenContradictions.length)} extracted file(s) contradict declared integrity; their observed bytes were written and are untrusted.`,
]),
...(nestedContradictions.length === 0
? []
: [
`${String(nestedContradictions.length)} nested integrity contradiction(s) were not written as their own files (${nestedContradictions.map(({ logical_path }) => logical_path).join(", ")}); their records describe inventory observations, not materialized files.`,
]),
],
});
};
@@ -216,30 +260,9 @@ interface LoadedInventory {
readonly manifest: ArtifactGraphManifest;
readonly occurrences: ReadonlyMap<string, ArtifactOccurrence>;
readonly nodes: ReadonlyMap<string, ArtifactNode>;
readonly integrityContradictions: readonly IntegrityContradiction[];
}
const collectOccurrences = (
items: readonly ArtifactOccurrence[],
selected: ReadonlySet<string>,
output: Map<string, ArtifactOccurrence>,
neededNodes: Set<string>,
): void => {
for (const item of items) {
if (!selected.has(item.occurrence_id)) continue;
output.set(item.occurrence_id, item);
if (item.artifact_id !== null) neededNodes.add(item.artifact_id);
}
};
const collectNodes = (
items: readonly ArtifactNode[],
selected: ReadonlySet<string>,
output: Map<string, ArtifactNode>,
): void => {
for (const item of items)
if (selected.has(item.artifact_id)) output.set(item.artifact_id, item);
};
const createReader = async (
path: string,
format: BinaryTarget["format"],
+11 -9
View File
@@ -1,4 +1,5 @@
import { z } from "incur";
import { artifactIntegrityPolicySchema } from "../domain/artifactGraph.js";
import { runProviderAnalysis } from "../composition/directAnalysis.js";
import { createArtifactExtractionDestination } from "../application/artifacts/ArtifactExtractionDestination.js";
@@ -193,14 +194,19 @@ const registerExtractionCommand = (cli: CliInstance, logger: Logger): void => {
args: z.object({
path: z.string().describe("Application or package path"),
}),
options: z.object({}),
run: ({ args }) =>
options: z.object({
integrityPolicy: artifactIntegrityPolicySchema.describe(
"Behavior when declared artifact integrity does not match",
),
}),
run: ({ args, options }) =>
logCliCommand(logger, "extract-artifact", () =>
runProviderAnalysis(
args.path,
"extract_artifact",
{
output_root: createArtifactExtractionDestination(),
integrity_policy: options.integrityPolicy,
},
logger,
),
@@ -216,14 +222,10 @@ const registerInspectionCommand = (cli: CliInstance, logger: Logger): void => {
path: z.string().describe("Application or package path"),
}),
options: z.object({
integrityPolicy: z
.enum(["fail", "record-and-continue"])
.default("fail")
.describe("Behavior when declared artifact integrity does not match"),
integrityPolicy: artifactIntegrityPolicySchema.describe(
"Behavior when declared artifact integrity does not match",
),
}),
alias: {
integrityPolicy: "integrity-policy",
},
run: ({ args, options }) =>
logCliCommand(logger, "inspect-artifact", () =>
runProviderAnalysis(
+11 -2
View File
@@ -1,4 +1,5 @@
import { z } from "incur";
import { artifactIntegrityPolicySchema } from "../domain/artifactGraph.js";
import { stat } from "node:fs/promises";
import { resolve } from "node:path";
@@ -51,7 +52,11 @@ const registerOverviewCommands = (
args: z.object({
path: z.string().describe("App, program, or analysis database path"),
}),
options: overviewOptions,
options: overviewOptions.extend({
integrityPolicy: artifactIntegrityPolicySchema.describe(
"Behavior when declared JavaScript artifact integrity does not match",
),
}),
run: ({ args, options, format }) =>
logCliCommand(logger, "analyze", () =>
runRoutedOverview(
@@ -123,6 +128,7 @@ const runRoutedOverview = async (
readonly snapshot?: string | undefined;
readonly "target-format"?: "dos-com" | undefined;
readonly provider?: string | undefined;
readonly integrityPolicy?: "fail" | "record-and-continue" | undefined;
},
logger: Logger,
output?: CliCommandOutput,
@@ -134,7 +140,10 @@ const runRoutedOverview = async (
(await isJavaScriptApplicationPath(path))
)
return runCliJavaScriptApplicationAnalysis(
{ input_path: resolve(path) },
{
input_path: resolve(path),
integrity_policy: options.integrityPolicy ?? "fail",
},
output,
);
return runDirectAnalysis(
+5 -1
View File
@@ -186,7 +186,11 @@ const registerJavaScriptApplicationCommand = (
run: ({ args, options, format }) =>
logCliCommand(logger, CLI_COMMANDS.analyzeJavaScriptApplication, () =>
runCliJavaScriptApplicationAnalysis(
{ input_path: args.path, format: options.artifactFormat },
{
input_path: args.path,
format: options.artifactFormat,
integrity_policy: options.integrityPolicy,
},
resultOutput === undefined
? undefined
: {
+4
View File
@@ -1,4 +1,5 @@
import { z } from "incur";
import { artifactIntegrityPolicySchema } from "./domain/artifactGraph.js";
/** Accept an agent-selected browser observation duration without an artificial ceiling. */
export const observationDuration = (fallback: number, minimum = 0) =>
@@ -63,4 +64,7 @@ export const javascriptApplicationOptions = z.object({
.enum(["auto", "asar", "directory"])
.default("auto")
.describe("Application artifact format"),
integrityPolicy: artifactIntegrityPolicySchema.describe(
"Behavior when declared artifact integrity does not match",
),
});
+7 -3
View File
@@ -8,17 +8,21 @@ import { requireOutputSchema } from "./toolOutputSchemaPrimitives.js";
import { appleAssetCatalogInputSchema } from "../domain/apple/appleAssetCatalog.js";
import { dylibResolutionInputSchema } from "../domain/apple/dylibResolution.js";
import { keyedArchiveInputSchema } from "../domain/apple/keyedArchive.js";
import { artifactIntegrityPolicySchema } from "../domain/artifactGraph.js";
/** Exact caller boundary for deterministic artifact inventory. */
export const artifactInventoryInputSchema = z.strictObject({
integrity_policy: z.enum(["fail", "record-and-continue"]).default("fail"),
integrity_policy: artifactIntegrityPolicySchema,
});
/** Extraction needs no selector: it materializes every regular child file. */
export const artifactExtractionInputSchema = z.strictObject({});
export const artifactExtractionInputSchema = z.strictObject({
integrity_policy: artifactIntegrityPolicySchema,
});
/** Provider input containing the destination chosen by the local adapter. */
export const artifactExtractionExecutionSchema = z.strictObject({
output_root: z.string().min(1),
integrity_policy: artifactIntegrityPolicySchema,
});
const exampleInputSchema = z.record(z.string(), jsonValueSchema);
@@ -68,7 +72,7 @@ export const ARTIFACT_TOOL_CONTRACTS = [
),
artifact(
"extract_artifact",
"Extract all regular files from the active archive or application package into a fresh temporary directory chosen by REA. The result includes its location. Rejects traversal and symlink escapes, never overwrites, enforces archive integrity checks, and verifies cleanup.",
"Extract all regular files from the active archive or application package into a fresh temporary directory chosen by REA. The result includes its location. Rejects traversal and symlink escapes, never overwrites, enforces archive integrity checks, and verifies cleanup. Integrity mismatches fail by default; record-and-continue extracts the observed bytes and reports each mismatch as an untrusted integrity contradiction.",
artifactExtractionInputSchema,
),
artifact(
@@ -79,7 +79,7 @@ export const ELECTRON_TOOL_CONTRACTS = [
name: "analyze_javascript_application",
...toolContractMetadata("analyze_javascript_application"),
description:
"Reconstruct one local ASAR or extracted JavaScript application as an inline application graph without executing it. Returns all recovered graph nodes, edges, semantic relations, limitations, and coverage.",
"Reconstruct one local ASAR or extracted JavaScript application as an inline application graph without executing it. Returns all recovered graph nodes, edges, semantic relations, limitations, and coverage. Integrity mismatches, such as unpacked native modules signed after packaging, fail by default; record-and-continue analyzes the observed bytes and reports each mismatch as an untrusted integrity contradiction.",
kind: "electron-provider",
inputSchema: analyzeJavaScriptApplicationInputSchema,
outputSchema: applicationOutputSchema,
+14 -1
View File
@@ -157,7 +157,11 @@ export const analysisErrorUserMessage = (error: AnalysisError): string => {
const standardMessage = standardErrorMessage(error._tag);
if (standardMessage !== undefined) return standardMessage;
if (error instanceof ArtifactOperationError)
return artifactMessage(error.reason);
return error.reason === "integrity" &&
error.artifactDetails !== undefined &&
INTEGRITY_POLICY_OPERATIONS.has(error.operation)
? "Artifact bytes contradict their declared integrity. If that is expected, such as an unpacked native module signed after packaging, rerun with the record-and-continue integrity policy (integrity_policy in MCP, --integrity-policy on the CLI) to keep the mismatch as an untrusted contradiction; otherwise get a fresh copy."
: artifactMessage(error.reason);
if (error instanceof EvidenceReferenceError)
return error.reason === "missing"
? `Evidence ${error.evidenceId} is not retained in this session. Supply complete inline Evidence, re-run its producer, or import its bundle before using this reference.`
@@ -245,6 +249,15 @@ const START_FAILURE_TAGS: ReadonlySet<AnalysisErrorTag> = new Set([
"HopperStartError",
]);
/** Operations whose callers can record integrity mismatches and continue. */
const INTEGRITY_POLICY_OPERATIONS: ReadonlySet<
ArtifactOperationError["operation"]
> = new Set([
"inspect_artifact",
"extract_artifact",
"analyze_javascript_application",
]);
const artifactMessage = (reason: ArtifactOperationError["reason"]): string => {
if (reason === "cancelled")
return "Artifact operation was cancelled. Start it again when ready.";
+7 -1
View File
@@ -122,8 +122,13 @@ const artifactOccurrenceSchema = z.object({
limitations: z.array(z.string()),
});
/** Behavior when observed bytes contradict declared artifact integrity. */
export const artifactIntegrityPolicySchema = z
.enum(["fail", "record-and-continue"])
.default("fail");
/** Observed bytes that contradict a container's declared integrity identity. */
const integrityContradictionSchema = z.object({
export const integrityContradictionSchema = z.object({
contradiction_id: contradictionIdSchema,
occurrence_id: occurrenceIdSchema,
parent_artifact_id: artifactIdSchema,
@@ -211,6 +216,7 @@ export const artifactExtractionResultSchema = z.object({
residual_paths: z.array(boundedRelativePathSchema),
}),
provenance: z.array(artifactCommandSchema),
integrity_contradictions: z.array(integrityContradictionSchema).default([]),
limitations: z.array(z.string()),
});
@@ -1,5 +1,9 @@
import { z } from "zod";
import {
artifactIntegrityPolicySchema,
integrityContradictionSchema,
} from "../artifactGraph.js";
import { javascriptApplicationGraphSchema } from "./javascriptApplicationGraph.js";
import { javaScriptSemanticGraphSchema } from "./javascriptSemanticGraph.js";
import { digestSchema } from "../digests.js";
@@ -11,6 +15,7 @@ const countSchema = z.number().int().min(0);
export const analyzeJavaScriptApplicationInputSchema = z.strictObject({
input_path: z.string().min(1),
format: z.enum(["auto", "asar", "directory"]).default("auto"),
integrity_policy: artifactIntegrityPolicySchema,
});
/** Compact counts for the high-level Electron architecture/security surface. */
@@ -62,6 +67,7 @@ export const javascriptApplicationAnalysisResultSchema = z
graph: javascriptApplicationGraphSchema,
summary: electronBoundarySummarySchema,
statistics: reconstructionStatisticsSchema,
integrity_contradictions: z.array(integrityContradictionSchema).default([]),
limitations: z.array(z.string().min(1)),
semantic_graph: javaScriptSemanticGraphSchema,
})
@@ -149,6 +149,8 @@ const comparisonLimitations = (
input: ApplicationVersionComparisonProjectionInput,
): string[] =>
uniqueSorted([
...input.left.graph.limitations,
...input.right.graph.limitations,
"Application comparison never uses bundler module ordinals as persistent identity and performs no fuzzy pairing.",
"Exact digest equality proves byte identity only; source-map, structural-fingerprint, and semantic-key matches retain inferred confidence.",
"Minified names and chunk locations are not assumed stable across versions.",
@@ -66,7 +66,11 @@ export const compareJavaScriptExportShapes = (
allChanges,
omittedChanges,
});
const limitations = comparisonLimitations(left, right, coverage.status);
const limitations = uniqueSorted([
...input.left.graph.limitations,
...input.right.graph.limitations,
...comparisonLimitations(left, right, coverage.status),
]);
const semantic = {
left: left.selection,
right: right.selection,
@@ -119,6 +119,7 @@ const noMatchResult = (
evidence_links: [input.sourceEvidenceId],
limitations: uniqueSorted([
"No graph entity matched the literal seed; this is not evidence that the feature is absent.",
...input.graph.limitations,
...sourceCoverageLimitations(input.graph),
]),
};
@@ -239,6 +240,7 @@ const traceCoverageStatus = (
const traceLimitations = (graph: JavaScriptApplicationGraph): string[] =>
uniqueSorted([
...graph.limitations,
"A trace reports graph relationships, not proof that code executed or that a feature is reachable in every state.",
"Static, native, passive-runtime, inferred, and unknown facts retain their original authority in the returned graph.",
"Native handoffs never open a binary or invoke a provider automatically; snapshot reuse remains provider/profile/target exact.",
-101
View File
@@ -1,101 +0,0 @@
import { z } from "zod";
/** Observed signing-directory metadata; policy interpretation belongs to the adapter. */
export const codeDirectorySchema = z.object({
version: z.string().nullable(),
flags: z
.object({
value: z.number().int().nonnegative(),
names: z.array(z.string()),
})
.nullable(),
code_slots: z.number().int().nonnegative().nullable(),
special_slots: z.number().int().nonnegative().nullable(),
location: z.string().nullable(),
hash_type: z.string().nullable(),
platform_identifier: z.number().int().nonnegative().nullable(),
runtime_version: z.string().nullable(),
executable_segment_flags: z.number().int().nonnegative().nullable(),
});
/** Observed sealed-resource summary. */
export const sealedResourcesSchema = z.object({
status: z.enum(["sealed", "none", "unknown"]),
version: z.number().int().nullable(),
rules: z.number().int().nullable(),
files: z.number().int().nullable(),
});
/** Local verification observation; unknown is distinct from a proven invalid signature. */
export const signatureVerificationSchema = z.object({
path: z.string(),
status: z.enum(["valid", "invalid", "unsigned", "unknown"]),
exit_code: z.number().int().nullable(),
diagnostics: z.array(z.string()),
validated_nested_code: z.array(z.string()),
prepared_nested_code: z.array(z.string()).default([]),
raw_stdout: z.string().default(""),
raw_stderr: z.string().default(""),
});
/** Local ticket presence and content identity, without a remote notarization claim. */
export const stapledTicketSchema = z.object({
status: z.enum(["present", "absent", "unreadable", "not-applicable"]),
path: z.string().nullable(),
sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
size: z.number().int().nonnegative().nullable(),
reason: z.string().nullable(),
});
const facetSchema = z.discriminatedUnion("facet", [
z.object({
facet: z.literal("library-validation"),
state: z.enum(["enforced", "disabled", "not-enforced", "unknown"]),
basis: z.literal("derived"),
evidence: z.array(z.string()),
explanation: z.string(),
}),
z.object({
facet: z.literal("dyld-environment-variables"),
state: z.enum(["ignored", "honored", "unknown"]),
basis: z.literal("derived"),
evidence: z.array(z.string()),
explanation: z.string(),
}),
z.object({
facet: z.literal("debugger-attach"),
state: z.enum(["allowed", "blocked", "unknown"]),
basis: z.literal("derived"),
evidence: z.array(z.string()),
explanation: z.string(),
}),
z.object({
facet: z.literal("executable-memory"),
state: z.enum([
"restricted",
"jit-allowed",
"unsigned-allowed",
"protection-disabled",
"unrestricted",
"unknown",
]),
basis: z.literal("derived"),
evidence: z.array(z.string()),
explanation: z.string(),
}),
z.object({
facet: z.literal("app-sandbox"),
state: z.enum(["sandboxed", "not-sandboxed", "unknown"]),
basis: z.literal("derived"),
evidence: z.array(z.string()),
explanation: z.string(),
}),
]);
/** Shared result semantics; adapters determine each facet's policy and evidence. */
export const securityFacetsSchema = z.array(facetSchema);
export type CodeDirectory = z.infer<typeof codeDirectorySchema>;
export type SecurityFacet = z.infer<typeof facetSchema>;
-12
View File
@@ -1,11 +1,4 @@
import { z } from "zod";
import {
codeDirectorySchema,
sealedResourcesSchema,
securityFacetsSchema,
signatureVerificationSchema,
stapledTicketSchema,
} from "./codeSigningPosture.js";
import { jsonValueSchema } from "../jsonValue.js";
const hexAddress = z.string().regex(/^0x[a-fA-F0-9]+$/u);
@@ -120,11 +113,6 @@ export const inspectSignatureSchema = z.object({
entitlements: jsonValueSchema.nullable(),
timestamp: z.string().nullable(),
hardened_runtime: z.boolean().nullable(),
code_directory: codeDirectorySchema.nullable(),
sealed_resources: sealedResourcesSchema,
verification: signatureVerificationSchema.nullable(),
stapled_ticket: stapledTicketSchema,
security_facets: securityFacetsSchema,
provenance: z.array(nativeCommandInvocationSchema),
limitations: z.array(z.string()),
});
-245
View File
@@ -1,245 +0,0 @@
import { describe, expect, it } from "vitest";
import {
codeDirectoryFlagNames,
deriveSecurityFacets,
} from "./CodeSigningPolicy.js";
import type { CodeDirectory } from "../domain/native/codeSigningPosture.js";
const directory = (
flags: number | null,
platform: number | null = null,
): CodeDirectory => ({
version: "20500",
flags:
flags === null
? null
: { value: flags, names: codeDirectoryFlagNames(flags) },
code_slots: 1,
special_slots: 7,
location: "embedded",
hash_type: "sha256",
platform_identifier: platform,
runtime_version: null,
executable_segment_flags: 1,
});
type PostureInput = Parameters<typeof deriveSecurityFacets>[0];
const derive = (
input: Omit<PostureInput, "mixedSlices" | "appleOrigin"> &
Partial<PostureInput>,
) => deriveSecurityFacets({ mixedSlices: false, appleOrigin: false, ...input });
const states = (facets: ReturnType<typeof deriveSecurityFacets>) =>
Object.fromEntries(facets.map(({ facet, state }) => [facet, state]));
const RUNTIME = 0x10000;
describe("CodeDirectory flags", () => {
it("names known bits and keeps unknown bits numeric", () => {
expect(codeDirectoryFlagNames(0x12a02)).toEqual([
"adhoc",
"kill",
"restrict",
"library-validation",
"runtime",
]);
expect(codeDirectoryFlagNames(0x40000 | 0x2)).toEqual(["adhoc", "0x40000"]);
});
});
describe("derived security facets", () => {
it("does not apply platform policy for a reported zero platform byte", () => {
expect(
states(
derive({
signed: true,
codeDirectory: directory(0x2, 0),
entitlements: null,
entitlementsKnown: true,
appleOrigin: true,
}),
),
).toMatchObject({
"library-validation": "not-enforced",
"dyld-environment-variables": "honored",
"debugger-attach": "allowed",
});
});
it("treats unsigned and plain ad hoc code as unrestricted", () => {
for (const signed of [false, true])
expect(
states(
derive({
signed,
codeDirectory: signed ? directory(0x2) : null,
entitlements: null,
entitlementsKnown: true,
}),
),
).toEqual({
"library-validation": "not-enforced",
"dyld-environment-variables": "honored",
"debugger-attach": "allowed",
"executable-memory": "unrestricted",
"app-sandbox": "not-sandboxed",
});
});
it("restricts hardened-runtime code unless entitlements relax it", () => {
expect(
states(
derive({
signed: true,
codeDirectory: directory(RUNTIME),
entitlements: { "com.apple.security.app-sandbox": true },
entitlementsKnown: true,
}),
),
).toEqual({
"library-validation": "enforced",
"dyld-environment-variables": "ignored",
"debugger-attach": "blocked",
"executable-memory": "restricted",
"app-sandbox": "sandboxed",
});
const relaxed = derive({
signed: true,
codeDirectory: directory(RUNTIME),
entitlements: {
"com.apple.security.cs.disable-library-validation": true,
"com.apple.security.cs.allow-dyld-environment-variables": true,
"com.apple.security.get-task-allow": true,
"com.apple.security.cs.allow-jit": true,
},
entitlementsKnown: true,
});
expect(states(relaxed)).toMatchObject({
"library-validation": "disabled",
"dyld-environment-variables": "honored",
"debugger-attach": "allowed",
"executable-memory": "jit-allowed",
});
expect(relaxed[0]?.evidence).toEqual([
"hardened runtime",
"com.apple.security.cs.disable-library-validation",
]);
});
it("lets explicit flags and platform identity override entitlements", () => {
const flagged = derive({
signed: true,
codeDirectory: directory(0x2000 | 0x800 | RUNTIME),
entitlements: {
"com.apple.security.cs.disable-library-validation": true,
},
entitlementsKnown: true,
});
expect(states(flagged)).toMatchObject({
"library-validation": "enforced",
"dyld-environment-variables": "ignored",
});
expect(
states(
derive({
signed: true,
codeDirectory: directory(RUNTIME, 26),
entitlements: null,
entitlementsKnown: true,
appleOrigin: true,
}),
),
).toMatchObject({
"library-validation": "enforced",
"dyld-environment-variables": "ignored",
"debugger-attach": "blocked",
});
});
});
describe("security facets that need more than one CodeDirectory", () => {
it("applies platform policy only to Apple-signed platform identifiers", () => {
const crafted = derive({
signed: true,
codeDirectory: directory(0, 26),
entitlements: null,
entitlementsKnown: true,
});
expect(states(crafted)).toMatchObject({
"library-validation": "unknown",
"dyld-environment-variables": "unknown",
"debugger-attach": "unknown",
});
expect(crafted[0]?.evidence).toEqual([
"platform identifier",
"Apple origin not verified",
]);
});
it("leaves every facet unknown when slices differ in signing state", () => {
const mixed = derive({
signed: true,
codeDirectory: directory(0x2000 | RUNTIME, 26),
entitlements: null,
entitlementsKnown: false,
appleOrigin: true,
mixedSlices: true,
});
expect(new Set(mixed.map(({ state }) => state))).toEqual(
new Set(["unknown"]),
);
expect(mixed[0]?.evidence).toEqual([
"architecture slices differ in signing state",
]);
});
it("leaves every facet unknown when verification failed", () => {
const invalid = derive({
signed: true,
codeDirectory: directory(0x2000 | RUNTIME, 26),
entitlements: null,
entitlementsKnown: true,
appleOrigin: true,
signatureInvalid: true,
});
expect(new Set(invalid.map(({ state }) => state))).toEqual(
new Set(["unknown"]),
);
expect(invalid[0]?.evidence).toEqual(["signature verification failed"]);
});
it("keeps facets unknown when flags or entitlements are unavailable", () => {
expect(
states(
derive({
signed: true,
codeDirectory: directory(RUNTIME),
entitlements: null,
entitlementsKnown: false,
}),
),
).toEqual({
"library-validation": "unknown",
"dyld-environment-variables": "unknown",
"debugger-attach": "unknown",
"executable-memory": "unknown",
"app-sandbox": "unknown",
});
expect(
states(
derive({
signed: true,
codeDirectory: directory(null),
entitlements: null,
entitlementsKnown: true,
}),
),
).toMatchObject({
"library-validation": "unknown",
"dyld-environment-variables": "unknown",
"debugger-attach": "unknown",
"executable-memory": "unknown",
});
});
});
-395
View File
@@ -1,395 +0,0 @@
import type { JsonValue } from "../domain/jsonValue.js";
import type {
CodeDirectory,
SecurityFacet,
} from "../domain/native/codeSigningPosture.js";
/** `SecCodeSignatureFlags` bits that codesign reports in a CodeDirectory. */
const CODE_DIRECTORY_FLAGS: readonly (readonly [number, string])[] = [
[0x1, "host"],
[0x2, "adhoc"],
[0x100, "hard"],
[0x200, "kill"],
[0x400, "expires"],
[0x800, "restrict"],
[0x1000, "enforcement"],
[0x2000, "library-validation"],
[0x10000, "runtime"],
[0x20000, "linker-signed"],
];
/** Decode CodeDirectory flag bits; unknown bits keep their hexadecimal value. */
export const codeDirectoryFlagNames = (value: number): string[] => {
const flags = value >>> 0;
const names = CODE_DIRECTORY_FLAGS.flatMap(([bit, name]) =>
(flags & bit) === 0 ? [] : [name],
);
const known = CODE_DIRECTORY_FLAGS.reduce((total, [bit]) => total | bit, 0);
for (let index = 0; index < 32; index++)
if (((flags >>> index) & 1) === 1 && ((known >>> index) & 1) === 0)
names.push(`0x${(2 ** index).toString(16)}`);
return names;
};
const entitlement = (
entitlements: JsonValue | null,
key: string,
): boolean | undefined => {
if (
entitlements === null ||
typeof entitlements !== "object" ||
Array.isArray(entitlements)
)
return undefined;
const value = entitlements[key];
return typeof value === "boolean" ? value : undefined;
};
interface PostureInput {
readonly signed: boolean;
readonly codeDirectory: CodeDirectory | null;
readonly entitlements: JsonValue | null;
/** False when mixed or unreadable signing states hide the aggregate entitlements. */
readonly entitlementsKnown: boolean;
/** Architecture slices differ in signing state, so no one CodeDirectory describes the process. */
readonly mixedSlices: boolean;
/**
* The signature satisfies `anchor apple`. Only then does a CodeDirectory
* platform identifier mean an Apple platform binary.
*/
readonly appleOrigin: boolean;
/**
* The local `--deep --strict` verification failed for the opened code.
* Flag bits from an unauthenticated CodeDirectory must not decide facets.
*/
readonly signatureInvalid?: boolean;
}
/** Whether the CodeDirectory claims a platform binary, and whether Apple signed it. */
const platformBinary = (
input: PostureInput,
): "apple" | "unverified" | "none" =>
(input.codeDirectory?.platform_identifier ?? 0) === 0
? "none"
: input.appleOrigin
? "apple"
: "unverified";
const UNVERIFIED_PLATFORM = [
"platform identifier",
"Apple origin not verified",
] as const;
const has = (input: PostureInput, flag: string): boolean =>
input.codeDirectory?.flags?.names.includes(flag) === true;
const libraryValidation = (input: PostureInput): SecurityFacet => {
const base = { facet: "library-validation", basis: "derived" } as const;
const explanation =
"With library validation, the process loads only libraries signed by Apple or by the same team; without it, any library dyld finds can load.";
if (!input.signed)
return {
...base,
state: "not-enforced",
evidence: ["unsigned"],
explanation,
};
if (input.codeDirectory === null || input.codeDirectory.flags === null)
return {
...base,
state: "unknown",
evidence: ["CodeDirectory flags unavailable"],
explanation,
};
const platform = platformBinary(input);
if (platform !== "none")
return platform === "apple"
? {
...base,
state: "enforced",
evidence: ["platform binary"],
explanation,
}
: {
...base,
state: "unknown",
evidence: [...UNVERIFIED_PLATFORM],
explanation,
};
if (has(input, "library-validation"))
return {
...base,
state: "enforced",
evidence: ["CodeDirectory flag library-validation"],
explanation,
};
if (!has(input, "runtime"))
return {
...base,
state: "not-enforced",
evidence: ["no hardened runtime or library-validation flag"],
explanation,
};
if (!input.entitlementsKnown)
return {
...base,
state: "unknown",
evidence: ["hardened runtime", "entitlements unavailable"],
explanation,
};
return entitlement(
input.entitlements,
"com.apple.security.cs.disable-library-validation",
) === true
? {
...base,
state: "disabled",
evidence: [
"hardened runtime",
"com.apple.security.cs.disable-library-validation",
],
explanation,
}
: {
...base,
state: "enforced",
evidence: ["hardened runtime"],
explanation,
};
};
const dyldEnvironment = (input: PostureInput): SecurityFacet => {
const base = {
facet: "dyld-environment-variables",
basis: "derived",
} as const;
const explanation =
"Whether dyld honors DYLD_* variables such as DYLD_INSERT_LIBRARIES at launch. setuid/setgid bits, a __RESTRICT segment, and system integrity policy can also restrict them and are not evaluated here.";
if (has(input, "restrict"))
return {
...base,
state: "ignored",
evidence: ["CodeDirectory flag restrict"],
explanation,
};
const platform = platformBinary(input);
if (platform !== "none")
return platform === "apple"
? {
...base,
state: "ignored",
evidence: ["platform binary"],
explanation,
}
: {
...base,
state: "unknown",
evidence: [...UNVERIFIED_PLATFORM],
explanation,
};
if (!has(input, "runtime"))
return input.signed && (input.codeDirectory?.flags ?? null) === null
? {
...base,
state: "unknown",
evidence: ["CodeDirectory flags unavailable"],
explanation,
}
: {
...base,
state: "honored",
evidence: ["no hardened runtime"],
explanation,
};
if (!input.entitlementsKnown)
return {
...base,
state: "unknown",
evidence: ["hardened runtime", "entitlements unavailable"],
explanation,
};
return entitlement(
input.entitlements,
"com.apple.security.cs.allow-dyld-environment-variables",
) === true
? {
...base,
state: "honored",
evidence: [
"hardened runtime",
"com.apple.security.cs.allow-dyld-environment-variables",
],
explanation,
}
: {
...base,
state: "ignored",
evidence: ["hardened runtime"],
explanation,
};
};
const debuggerAttach = (input: PostureInput): SecurityFacet => {
const base = { facet: "debugger-attach", basis: "derived" } as const;
const explanation =
"Whether a debugger running as the same user can obtain the task port. Developer Tools authorization and system integrity policy still apply.";
if (
input.entitlementsKnown &&
entitlement(input.entitlements, "com.apple.security.get-task-allow") ===
true
)
return {
...base,
state: "allowed",
evidence: ["com.apple.security.get-task-allow"],
explanation,
};
const platform = platformBinary(input);
if (platform !== "none")
return platform === "apple"
? {
...base,
state: "blocked",
evidence: ["platform binary"],
explanation,
}
: {
...base,
state: "unknown",
evidence: [...UNVERIFIED_PLATFORM],
explanation,
};
if (has(input, "runtime"))
return input.entitlementsKnown
? {
...base,
state: "blocked",
evidence: ["hardened runtime without get-task-allow"],
explanation,
}
: {
...base,
state: "unknown",
evidence: ["hardened runtime", "entitlements unavailable"],
explanation,
};
if (input.signed && (input.codeDirectory?.flags ?? null) === null)
return {
...base,
state: "unknown",
evidence: ["CodeDirectory flags unavailable"],
explanation,
};
return {
...base,
state: "allowed",
evidence: ["no hardened runtime"],
explanation,
};
};
const executableMemory = (input: PostureInput): SecurityFacet => {
const base = { facet: "executable-memory", basis: "derived" } as const;
const explanation =
"Hardened-runtime limits on writable or unsigned executable memory, relaxed by code-signing entitlements.";
if (!has(input, "runtime"))
return input.signed && (input.codeDirectory?.flags ?? null) === null
? {
...base,
state: "unknown",
evidence: ["CodeDirectory flags unavailable"],
explanation,
}
: {
...base,
state: "unrestricted",
evidence: ["no hardened runtime"],
explanation,
};
if (!input.entitlementsKnown)
return {
...base,
state: "unknown",
evidence: ["hardened runtime", "entitlements unavailable"],
explanation,
};
for (const [key, state] of [
[
"com.apple.security.cs.disable-executable-page-protection",
"protection-disabled",
],
[
"com.apple.security.cs.allow-unsigned-executable-memory",
"unsigned-allowed",
],
["com.apple.security.cs.allow-jit", "jit-allowed"],
] as const)
if (entitlement(input.entitlements, key) === true)
return {
...base,
state,
evidence: ["hardened runtime", key],
explanation,
};
return {
...base,
state: "restricted",
evidence: ["hardened runtime"],
explanation,
};
};
const appSandbox = (input: PostureInput): SecurityFacet => {
const base = { facet: "app-sandbox", basis: "derived" } as const;
const explanation =
"Whether the App Sandbox entitlement confines the process.";
if (!input.entitlementsKnown)
return {
...base,
state: "unknown",
evidence: ["entitlements unavailable"],
explanation,
};
return entitlement(input.entitlements, "com.apple.security.app-sandbox") ===
true
? {
...base,
state: "sandboxed",
evidence: ["com.apple.security.app-sandbox"],
explanation,
}
: {
...base,
state: "not-sandboxed",
evidence: ["no com.apple.security.app-sandbox entitlement"],
explanation,
};
};
/** Derive launch-time security facets from observed flags and entitlements. */
export const deriveSecurityFacets = (input: PostureInput): SecurityFacet[] => {
const facets = [
libraryValidation(input),
dyldEnvironment(input),
debuggerAttach(input),
executableMemory(input),
appSandbox(input),
];
// An invalid main signature leaves flag bits unauthenticated; keep the raw
// CodeDirectory fields but report every facet as unknown.
if (input.signatureInvalid === true)
return facets.map((facet) => ({
...facet,
state: "unknown" as const,
evidence: ["signature verification failed"],
}));
// Each slice runs under its own signature; the inspected one does not
// describe an unsigned slice of the same file.
return input.mixedSlices
? facets.map((facet) => ({
...facet,
state: "unknown" as const,
evidence: ["architecture slices differ in signing state"],
}))
: facets;
};
-141
View File
@@ -1,141 +0,0 @@
import type { InspectSignature } from "../domain/native/nativeInspection.js";
import type { NativeCommandCapture } from "./CommandRunner.js";
/** Strip the diagnostic's echoed pathname for classification, keeping the raw line elsewhere. */
export const codesignReason = (line: string, path: string): string => {
if (line.startsWith(`${path}: `)) return line.slice(path.length + 2);
if (line.startsWith("/") || line.startsWith(`${path}/`)) {
const delimiter = line.lastIndexOf(": ");
return delimiter >= 0 ? line.slice(delimiter + 2) : "";
}
return line;
};
/** Remove the complete selected path before splitting lines, including embedded LF bytes. */
export const codesignReasons = (
capture: NativeCommandCapture,
path: string,
): string[] => {
const observed = `${capture.stderr}\n${capture.stdout}`;
const text =
path.length === 0 ? observed : observed.split(path).join("$SELECTED_PATH");
const lines = text.split("\n");
const progress = lines.some((line) =>
/^--(?:prepared|validated):/u.test(line),
);
return (
lines
.filter((line) => !/^--(?:prepared|validated):/u.test(line))
// Unprefixed continuation text can belong to an unescaped nested filename.
// Keep it as raw evidence, but do not turn it into a verification reason.
.filter(
(line) =>
!progress ||
line.startsWith("$SELECTED_PATH: ") ||
line.startsWith("$SELECTED_PATH/"),
)
.map((line) => codesignReason(line, "$SELECTED_PATH"))
);
};
/** Classify only explicit diagnostic reasons; nonzero exit alone proves no invalidity. */
const operationalReason = (reason: string): boolean =>
/^(?:permission denied|operation not permitted|EACCES\b|EPERM\b|I\/O error|input\/output error)/iu.test(
reason,
);
/**
* Definitive codesign rejections. A nonzero exit whose text is not in this
* list, and is not an operational failure, stays `unknown` so an unrecognized
* diagnostic is not reported as a broken signature.
*/
const INVALID_SIGNATURE_REASONS = [
"a resource envelope is obsolete",
"a sealed resource is missing or invalid",
"bundle format unrecognized, invalid, or unsuitable",
"code or signature modified",
"file added:",
"file modified:",
"invalid or unsupported format",
"invalid signature",
"main executable failed strict validation",
"resource envelope is obsolete",
"resource fork, Finder information, or similar detritus not allowed",
"signature is invalid",
"unsealed contents present",
] as const;
const invalidSignatureReason = (reason: string): boolean => {
const text = reason.toLowerCase();
return INVALID_SIGNATURE_REASONS.some((phrase) =>
text.startsWith(phrase.toLowerCase()),
);
};
/** Operational diagnostics can coexist with an independently proven invalid component. */
export const codesignOperationalFailure = (
capture: NativeCommandCapture,
path: string,
): boolean => codesignReasons(capture, path).some(operationalReason);
const verificationStatus = (
capture: NativeCommandCapture,
reasons: readonly string[],
unsigned: boolean,
): NonNullable<InspectSignature["verification"]>["status"] => {
if (capture.exitCode === 0) return "valid";
const unsignedReason = reasons.some((reason) =>
/^(?:code object is not signed at all|code object is not signed|not signed at all)/iu.test(
reason,
),
);
if (reasons.some(invalidSignatureReason)) return "invalid";
if (unsignedReason && !unsigned) return "invalid";
if (reasons.some(operationalReason)) return "unknown";
if (unsignedReason) return "unsigned";
return "unknown";
};
/** Project codesign verification without changing pathname bytes or discarding diagnostics. */
export const signatureVerification = (
capture: NativeCommandCapture,
path: string,
unsigned: boolean,
progressCompleteness: "complete" | "ambiguous" = "complete",
): NonNullable<InspectSignature["verification"]> => {
const lines = `${capture.stderr}\n${capture.stdout}`
.split("\n")
.filter((line) => line.length > 0);
const diagnostics = lines.filter(
(line) => !/^--(?:prepared|validated):/u.test(line),
);
return {
path,
status:
progressCompleteness === "ambiguous" && capture.exitCode !== 0
? "unknown"
: verificationStatus(capture, codesignReasons(capture, path), unsigned),
exit_code: capture.exitCode,
diagnostics,
prepared_nested_code: [
...new Set(
lines.flatMap((line) =>
line.startsWith("--prepared:")
? [line.slice("--prepared:".length)]
: [],
),
),
].sort(),
raw_stdout: capture.stdout,
raw_stderr: capture.stderr,
validated_nested_code: [
...new Set(
lines.flatMap((line) =>
line.startsWith("--validated:")
? [line.slice("--validated:".length)]
: [],
),
),
].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)),
};
};
+208 -16
View File
@@ -8,7 +8,7 @@ import { observeNativeUi } from "./NativeUiObservation.js";
import { LldbCallTracer, type NativeCallTracer } from "./LldbCallTracer.js";
import { observeNativeCalls } from "./NativeCallObservation.js";
import { dirname, isAbsolute, resolve } from "node:path";
import { open, stat } from "node:fs/promises";
import { open, realpath, stat } from "node:fs/promises";
import { z } from "zod";
@@ -25,6 +25,7 @@ import {
type NativeToolName,
} from "../contracts/native/nativeToolContracts.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import type { EvidenceLocation } from "../domain/evidence.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
@@ -35,9 +36,14 @@ import { BinaryTargetError } from "../domain/configurationErrors.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import {
omittedPrototypeKeysLimitation,
parseXmlPropertyList,
} from "../domain/propertyListKeys.js";
import {
demangleSwiftSchema,
inspectPlistSchema,
inspectSignatureSchema,
listArchitecturesSchema,
type NativeCommandInvocation,
} from "../domain/native/nativeInspection.js";
@@ -48,8 +54,7 @@ import {
type NativeCommandCapture,
type NativeCommandRunner,
} from "./CommandRunner.js";
import { inspectNativeSignature } from "./NativeSignatureInspection.js";
import type { NativeObservation } from "./NativeObservation.js";
import { parseCodeSignature } from "./parsers/codesign.js";
import { parseDemangledSymbols } from "./parsers/demangle.js";
import { parseLipoArchitectures } from "./parsers/lipo.js";
import {
@@ -203,10 +208,6 @@ class NativeMacOSClient implements AnalysisClient {
)
: observation;
} catch (cause: unknown) {
if (cause instanceof AnalysisError) return err(cause);
// A helper that observed the abort escapes as a DOMException.
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(operation));
return err(
new AnalysisOutputError(operation, "Native output parsing failed", {
cause,
@@ -317,16 +318,127 @@ class NativeMacOSClient implements AnalysisClient {
async #inspectSignature(
signal?: AbortSignal,
): Promise<Result<NativeObservation, AnalysisError>> {
return inspectNativeSignature({
target: this.target,
capture: (argv, commandSignal) =>
this.#run("inspect_signature", "codesign", argv, {
signal: commandSignal,
acceptNonZero: true,
}),
invocation: (capture) => invocation(capture, this.target.path),
...(signal === undefined ? {} : { signal }),
const display = await this.#run(
"inspect_signature",
"codesign",
["-d", "--verbose=4", this.target.path],
{ signal, acceptNonZero: true },
);
if (!display.ok) return display;
const unsigned = isNonzeroUnsignedObservation(display.value);
const displayFailure = codeSignCaptureFailure(display.value);
if (displayFailure !== null) return err(displayFailure);
const requirements = await this.#run(
"inspect_signature",
"codesign",
["-d", "-r-", this.target.path],
{ signal, acceptNonZero: true },
);
if (!requirements.ok) return requirements;
const requirementsFailure = codeSignCaptureFailure(requirements.value);
if (requirementsFailure !== null) return err(requirementsFailure);
const entitlements = await this.#run(
"inspect_signature",
"codesign",
["-d", "--entitlements", ":-", this.target.path],
{ signal, acceptNonZero: true },
);
if (!entitlements.ok) return entitlements;
const entitlementsFailure = codeSignCaptureFailure(entitlements.value);
if (entitlementsFailure !== null) return err(entitlementsFailure);
// codesign echoes the resolved executable path in its diagnostics.
const parsed = parseCodeSignature(display.value.stderr, unsigned, [
this.target.path,
...(await canonicalPath(this.target.path)),
]);
// The requirement is printed to stdout; stderr echoes the path.
const requirementText =
/designated\s*=>\s*(.+)$/mu.exec(requirements.value.stdout)?.[1] ?? null;
// Entitlements XML is printed to stdout; stderr echoes the path.
const entitlementValue = parseEntitlements(entitlements.value.stdout);
const captures = [display.value, requirements.value, entitlements.value];
const limitations = [
...parsed.limitations,
...(entitlementValue.omittedPrototypeKeys === 0
? []
: [
`Entitlements: ${omittedPrototypeKeysLimitation(entitlementValue.omittedPrototypeKeys)}`,
]),
];
const mixedSigning =
!unsigned &&
(isNonzeroUnsignedObservation(requirements.value) ||
isNonzeroUnsignedObservation(entitlements.value));
if (mixedSigning) {
const slices = await this.#inspectMixedSignatureSlices(
parsed.format,
requirements.value.exitCode !== 0,
entitlements.value.exitCode !== 0,
signal,
);
if (!slices.ok) return slices;
captures.push(...slices.value.captures);
limitations.push(...slices.value.limitations);
}
const provenance = captures.map((capture) =>
invocation(capture, this.target.path),
);
const result = inspectSignatureSchema.parse({
...parsed,
designated_requirement: requirementText,
entitlements: entitlementValue.value,
provenance,
limitations,
});
return ok({
result: jsonValueSchema.parse(result),
provenance,
limitations: result.limitations,
locations: [],
});
}
async #inspectMixedSignatureSlices(
format: string | null,
requirementsUnavailable: boolean,
entitlementsUnavailable: boolean,
signal?: AbortSignal,
): Promise<Result<MixedSignatureSlices, AnalysisError>> {
const captures: NativeCommandCapture[] = [];
const unsigned: string[] = [];
const unclassified: string[] = [];
for (const architecture of codeSignArchitectures(format, this.target)) {
const slice = await this.#run(
"inspect_signature",
"codesign",
["-d", "-a", architecture, "--verbose=4", this.target.path],
{ signal, acceptNonZero: true },
);
if (!slice.ok) return slice;
captures.push(slice.value);
if (slice.value.exitCode === 0) continue;
if (isNonzeroUnsignedObservation(slice.value))
unsigned.push(architecture);
else unclassified.push(architecture);
}
const limitations = [
unsigned.length > 0
? `Unsigned Mach-O slices: ${unsigned.join(", ")}.`
: "One or more Mach-O slices are unsigned, but their architectures could not be classified.",
];
if (unclassified.length > 0)
limitations.push(
`Signature state could not be classified for Mach-O slices: ${unclassified.join(", ")}.`,
);
if (requirementsUnavailable)
limitations.push(
"The aggregate designated requirement is unavailable because Mach-O slices have mixed signing states.",
);
if (entitlementsUnavailable)
limitations.push(
"The aggregate entitlements are unavailable because Mach-O slices have mixed signing states.",
);
return ok({ captures, limitations });
}
async #inspectPlist(
@@ -451,6 +563,18 @@ class NativeMacOSClient implements AnalysisClient {
}
}
interface NativeObservation {
readonly result: JsonValue;
readonly provenance: readonly NativeCommandInvocation[];
readonly limitations: readonly string[];
readonly locations: readonly EvidenceLocation[];
}
interface MixedSignatureSlices {
readonly captures: readonly NativeCommandCapture[];
readonly limitations: readonly string[];
}
const isNativeOperation = (
operation: AnalysisOperation,
): operation is NativeToolName =>
@@ -471,6 +595,62 @@ const translateCommandFailure = (
return new ProviderAdapterError(IDENTITY.id, operation, { cause: failure });
};
const translateCodeSignExitFailure = (
capture: NativeCommandCapture,
): AnalysisError =>
translateCommandFailure(
"inspect_signature",
new NativeCommandFailure("codesign", "nonzero-exit", capture.exitCode),
);
const commandOutput = (capture: NativeCommandCapture): string =>
`${capture.stdout}\n${capture.stderr}`;
/**
* A signed artifact exits zero; its diagnostics can still contain this text
* through the echoed path or identifier.
*/
const isNonzeroUnsignedObservation = (capture: NativeCommandCapture): boolean =>
capture.exitCode !== null &&
capture.exitCode !== 0 &&
/not signed at all|code object is not signed/iu.test(commandOutput(capture));
const canonicalPath = async (path: string): Promise<string[]> => {
try {
return [await realpath(path)];
} catch {
return [];
}
};
const codeSignCaptureFailure = (
capture: NativeCommandCapture,
): AnalysisError | null =>
capture.exitCode === 0 || isNonzeroUnsignedObservation(capture)
? null
: translateCodeSignExitFailure(capture);
const codeSignArchitectures = (
format: string | null,
target: BinaryTarget,
): string[] => {
const universal = /^Mach-O universal \(([^)\r\n]+)\)$/u.exec(
format ?? "",
)?.[1];
if (universal !== undefined) {
const architectures = universal
.split(/\s+/u)
.filter((architecture) =>
/^(?:i386|x86_64|armv7|arm64|arm64e)$/u.test(architecture),
);
if (architectures.length > 0) return [...new Set(architectures)];
}
if (target.kind !== "executable" || target.format !== "mach-o") return [];
return target.availableArchitectures.map((architecture) =>
architecture === "x86" ? "i386" : architecture,
);
};
const invocation = (
capture: NativeCommandCapture,
artifactPath: string,
@@ -491,6 +671,18 @@ const invocation = (
stderr_bytes: capture.stderrBytes,
});
const parseEntitlements = (
output: string,
): { readonly value: JsonValue; readonly omittedPrototypeKeys: number } => {
const start = output.indexOf("<?xml");
const end = output.lastIndexOf("</plist>");
if (start < 0 || end < start) return { value: null, omittedPrototypeKeys: 0 };
const { value, omittedPrototypeKeys } = parseXmlPropertyList(
output.slice(start, end + "</plist>".length),
);
return { value: jsonValueSchema.parse(value), omittedPrototypeKeys };
};
/**
* Report a plist that cannot be decoded as the caller's selection, or as the
* target's missing default, rather than as a failed tool run.
-78
View File
@@ -1,78 +0,0 @@
import { expect, it } from "vitest";
import { inspectNestedCodePaths } from "./NativeNestedCode.js";
it("observes cancellation between nested filesystem lookups", async () => {
const controller = new AbortController();
const paths: string[] = [];
await expect(
inspectNestedCodePaths(
{
validated_nested_code: ["/app/first", "/app/second"],
},
controller.signal,
{
lookup: async (path) => {
paths.push(path);
controller.abort();
},
names: async () => [],
},
),
).rejects.toMatchObject({ name: "AbortError" });
expect(paths).toEqual(["/app/first"]);
});
it("checks prepared-only fragments with the same completeness rules", async () => {
const warnings = await inspectNestedCodePaths(
{ prepared_nested_code: ["/app/odd"], validated_nested_code: [] },
undefined,
{
lookup: async () => {
throw Object.assign(new Error("not found"), { code: "ENOENT" });
},
names: async () => [],
},
);
expect(warnings.limitations).toContainEqual(
expect.stringContaining(
'prepared nested code at "/app/odd", which does not exist',
),
);
});
it.each(["EACCES", "EPERM", "EIO", "ESTALE"])(
"keeps observed records when path lookup fails with %s",
async (code) => {
const result = await inspectNestedCodePaths(
{
prepared_nested_code: ["/app/first"],
validated_nested_code: ["/app/second"],
},
undefined,
{
lookup: async () => {
throw Object.assign(new Error("lookup failed"), { code });
},
names: async () => [],
},
);
expect(result.limitations).toHaveLength(2);
expect(result.limitations.every((message) => message.includes(code))).toBe(
true,
);
expect(result.progressAmbiguous).toBe(true);
},
);
it("detects newline ambiguity even when the reported first fragment does not exist", async () => {
const result = await inspectNestedCodePaths(
{ prepared_nested_code: ["/app/odd"], validated_nested_code: [] },
undefined,
{
lookup: async () => {
throw Object.assign(new Error("missing"), { code: "ENOENT" });
},
names: async () => ["odd\n/app: invalid signature"],
},
);
expect(result.progressAmbiguous).toBe(true);
});
-105
View File
@@ -1,105 +0,0 @@
import { lstat, readdir } from "node:fs/promises";
import { dirname, basename } from "node:path";
/** Filesystem seam for path-completeness checks and cancellation regressions. */
export interface NativeNestedPathView {
lookup(path: string): Promise<void>;
names(directory: string): Promise<string[]>;
}
const FILE_SYSTEM: NativeNestedPathView = {
lookup: async (path) => {
await lstat(path);
},
names: (path) => readdir(path),
};
const errorCode = (cause: unknown) =>
cause instanceof Error && "code" in cause ? cause.code : undefined;
/** Completeness of newline-delimited progress records, distinct from verification. */
export interface NestedCodePathInspection {
readonly limitations: readonly string[];
readonly progressAmbiguous: boolean;
}
/** Preserve reported paths and operational errors, and identify ambiguous progress. */
export const inspectNestedCodePaths = async (
verification: {
readonly validated_nested_code: readonly string[];
readonly prepared_nested_code?: readonly string[];
},
signal?: AbortSignal,
view: NativeNestedPathView = FILE_SYSTEM,
): Promise<NestedCodePathInspection> => {
signal?.throwIfAborted();
const limitations: string[] = [];
const directories = new Map<string, Promise<ReadonlySet<string>>>();
let progressAmbiguous = false;
const records = new Map<string, "prepared" | "validated">();
for (const path of verification.prepared_nested_code ?? [])
records.set(path, "prepared");
for (const path of verification.validated_nested_code)
records.set(path, "validated");
for (const [path, record] of records) {
signal?.throwIfAborted();
try {
await view.lookup(path);
} catch (cause: unknown) {
signal?.throwIfAborted();
const code = errorCode(cause);
if (code === "EACCES" || code === "EPERM") {
progressAmbiguous = true;
limitations.push(
`Could not confirm completeness of codesign nested path ${JSON.stringify(path)}: permission denied (${code}); the reported path may be a fragment.`,
);
continue;
}
if (code === "ENOENT" || code === "ENOTDIR")
limitations.push(
`codesign reported ${record} nested code at ${JSON.stringify(path)}, which does not exist; structured nested-code records may hold fragments of a path containing a newline.`,
);
else {
progressAmbiguous = true;
limitations.push(
`Could not confirm completeness of codesign nested path ${JSON.stringify(path)}: ${cause instanceof Error ? cause.message : String(cause)} (${String(code ?? "unknown")}); the reported path may be a fragment.`,
);
}
}
signal?.throwIfAborted();
const parent = dirname(path);
let names = directories.get(parent);
if (names === undefined) {
names = view
.names(parent)
.then(
(entries) =>
new Set(
entries
.filter((name) => name.includes("\n"))
.map((name) => name.slice(0, name.indexOf("\n"))),
),
);
directories.set(parent, names);
}
try {
const prefixes = await names;
const ambiguous = prefixes.has(basename(path));
signal?.throwIfAborted();
if (ambiguous) {
progressAmbiguous = true;
limitations.push(
`codesign reported ${record} nested code at ${JSON.stringify(path)}, which could be the first line of a nested path containing a newline; structured nested-code records are ambiguous and should not be trusted as complete.`,
);
}
} catch (cause: unknown) {
signal?.throwIfAborted();
progressAmbiguous = true;
limitations.push(
`Could not confirm completeness of codesign nested path ${JSON.stringify(path)} from parent directory ${JSON.stringify(parent)}: ${cause instanceof Error ? cause.message : String(cause)}`,
);
}
}
signal?.throwIfAborted();
return { limitations, progressAmbiguous };
};
-11
View File
@@ -1,11 +0,0 @@
import type { JsonValue } from "../domain/jsonValue.js";
import type { EvidenceLocation } from "../domain/evidence.js";
import type { NativeCommandInvocation } from "../domain/native/nativeInspection.js";
/** Provider observation before shared execution/Evidence projection. */
export interface NativeObservation {
readonly result: JsonValue;
readonly provenance: readonly NativeCommandInvocation[];
readonly limitations: readonly string[];
readonly locations: readonly EvidenceLocation[];
}
-15
View File
@@ -1,15 +0,0 @@
import { parseXmlPropertyList } from "../domain/propertyListKeys.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
/** Parse the XML entitlement document within codesign output, retaining omission evidence. */
export const parseSignatureEntitlements = (
output: string,
): { readonly value: JsonValue; readonly omittedPrototypeKeys: number } => {
const start = output.indexOf("<?xml");
const end = output.lastIndexOf("</plist>");
if (start < 0 || end < start) return { value: null, omittedPrototypeKeys: 0 };
const { value, omittedPrototypeKeys } = parseXmlPropertyList(
output.slice(start, end + "</plist>".length),
);
return { value: jsonValueSchema.parse(value), omittedPrototypeKeys };
};
-234
View File
@@ -1,234 +0,0 @@
import { realpath } from "node:fs/promises";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import {
inspectSignatureSchema,
type NativeCommandInvocation,
} from "../domain/native/nativeInspection.js";
import { deriveSecurityFacets } from "./CodeSigningPolicy.js";
import {
bindSignatureTarget,
verifySignatureTarget,
} from "./SignatureTargetBinding.js";
import { omittedPrototypeKeysLimitation } from "../domain/propertyListKeys.js";
import { err, ok, type Result } from "../domain/result.js";
import {
NativeCommandFailure,
type NativeCommandCapture,
} from "./CommandRunner.js";
import { NATIVE_MACOS_PROVIDER_IDENTITY } from "./NativeMacOSProviderMetadata.js";
import type { NativeObservation } from "./NativeObservation.js";
import {
signatureVerification,
codesignOperationalFailure,
codesignReasons,
} from "./CodesignVerification.js";
import { parseCodeSignature } from "./parsers/codesign.js";
import { parseSignatureEntitlements } from "./NativeSignatureEntitlements.js";
import {
inspectSignatureSlices,
unsignedSignatureCapture,
type SignatureCapture,
} from "./NativeSignatureProbes.js";
import {
SIGNATURE_POSTURE_LIMITATIONS,
signedCodePath,
stapledTicket,
} from "./NativeSignaturePosture.js";
import { inspectNestedCodePaths } from "./NativeNestedCode.js";
interface SignatureDisplays {
readonly display: NativeCommandCapture;
readonly requirements: NativeCommandCapture;
readonly entitlements: NativeCommandCapture;
}
/** Display failures and unsigned observations use the same reason parser as verification. */
const signatureDisplays = async (
path: string,
capture: SignatureCapture,
signal?: AbortSignal,
): Promise<Result<SignatureDisplays, AnalysisError>> => {
const display = await capture(["-d", "--verbose=4", path], signal);
if (!display.ok) return display;
const requirements = await capture(["-d", "-r-", path], signal);
if (!requirements.ok) return requirements;
const entitlements = await capture(
["-d", "--entitlements", ":-", path],
signal,
);
if (!entitlements.ok) return entitlements;
for (const result of [
display.value,
requirements.value,
entitlements.value,
]) {
if (result.exitCode !== 0 && !unsignedSignatureCapture(result, path))
return err(
new ProviderAdapterError(
NATIVE_MACOS_PROVIDER_IDENTITY.id,
"inspect_signature",
{
diagnostics: {
path,
tool: result.tool,
arguments: [...result.arguments],
exit_code: result.exitCode,
signal: result.signal,
raw_stdout: result.stdout,
raw_stderr: result.stderr,
},
cause: new NativeCommandFailure(
"codesign",
"nonzero-exit",
result.exitCode,
),
},
),
);
}
return ok({
display: display.value,
requirements: requirements.value,
entitlements: entitlements.value,
});
};
/** Compose displays, independent slice knowledge, verification, and local ticket evidence. */
export const inspectNativeSignature = async (options: {
readonly target: BinaryTarget;
readonly capture: SignatureCapture;
readonly invocation: (
capture: NativeCommandCapture,
) => NativeCommandInvocation;
readonly signal?: AbortSignal;
}): Promise<Result<NativeObservation, AnalysisError>> => {
const { target, capture, signal } = options;
const binding = await bindSignatureTarget(target, signal);
if (!binding.ok) return binding;
const displays = await signatureDisplays(target.path, capture, signal);
if (!displays.ok) return displays;
const { display, requirements, entitlements } = displays.value;
const unsigned = unsignedSignatureCapture(display, target.path);
let canonical: string[] = [];
try {
canonical = [await realpath(target.path)];
} catch {
/* The display retains the observed path. */
}
const parsed = parseCodeSignature(display.stderr, unsigned, [
target.path,
...canonical,
]);
const entitlementValue = parseSignatureEntitlements(entitlements.stdout);
const code = signedCodePath(target);
const verify = (path: string) =>
capture(["--verify", "--deep", "--strict", "--verbose=2", path], signal);
const verified = await verify(code);
if (!verified.ok) return verified;
const captures = [display, requirements, entitlements, verified.value];
let appleOrigin = false;
let appleOriginFailure: string | undefined;
if (!unsigned && (parsed.code_directory?.platform_identifier ?? 0) !== 0) {
const anchor = await capture(["--verify", "-R=anchor apple", code], signal);
if (!anchor.ok) return anchor;
captures.push(anchor.value);
appleOrigin = anchor.value.exitCode === 0;
if (!appleOrigin) {
const reason = codesignReasons(anchor.value, code)
.filter((line) => line.trim().length > 0)
.join("\n");
appleOriginFailure = reason || `codesign exited ${anchor.value.exitCode}`;
}
}
const slices = await inspectSignatureSlices(
target,
{ format: parsed.format, requirements, entitlements, unsigned },
capture,
signal,
);
if (!slices.ok) return slices;
captures.push(...slices.value.captures);
const aggregateUnsigned =
slices.value.signed === undefined ? unsigned : !slices.value.signed;
// Verification is independent evidence: uncertain display probes must not
// erase an explicit signature failure from the verifier.
const reportedVerification = signatureVerification(
verified.value,
code,
aggregateUnsigned,
);
const nestedPaths = await inspectNestedCodePaths(
reportedVerification,
signal,
);
const verification = nestedPaths.progressAmbiguous
? signatureVerification(
verified.value,
code,
aggregateUnsigned,
"ambiguous",
)
: reportedVerification;
const limitations = [
...parsed.limitations,
...SIGNATURE_POSTURE_LIMITATIONS,
...slices.value.limitations,
...nestedPaths.limitations,
];
if (entitlementValue.omittedPrototypeKeys !== 0)
limitations.push(
`Entitlements: ${omittedPrototypeKeysLimitation(entitlementValue.omittedPrototypeKeys)}`,
);
if (appleOriginFailure !== undefined)
limitations.push(`Apple-origin check failed: ${appleOriginFailure}`);
if (verification.status === "unknown")
limitations.push(
"Signature verification is inconclusive (permission, I/O or unrecognized diagnostic); this is not a proven broken signature.",
);
else if (codesignOperationalFailure(verified.value, code))
limitations.push(
"Some code could not be verified due to operational diagnostics; definitive signature failures elsewhere still prove invalidity.",
);
let mainInvalid =
verification.status === "invalid" || verification.status === "unknown";
if (mainInvalid && !unsigned && code !== target.path) {
const main = await verify(target.path);
if (!main.ok) return main;
captures.push(main.value);
mainInvalid = main.value.exitCode !== 0;
}
const provenance = captures.map(options.invocation);
const ticket = await stapledTicket(target, signal);
const version = await verifySignatureTarget(target, binding.value, signal);
if (!version.ok) return version;
const facets = deriveSecurityFacets({
signed: !aggregateUnsigned,
codeDirectory: parsed.code_directory,
entitlements: entitlementValue.value,
entitlementsKnown: unsigned || entitlements.exitCode === 0,
mixedSlices: slices.value.mixed,
appleOrigin,
signatureInvalid: mainInvalid,
});
const result = inspectSignatureSchema.parse({
...parsed,
signed: !aggregateUnsigned,
designated_requirement:
/designated\s*=>\s*(.+)$/mu.exec(requirements.stdout)?.[1] ?? null,
entitlements: entitlementValue.value,
verification,
stapled_ticket: ticket,
security_facets: facets,
provenance,
limitations,
});
return ok({
result: jsonValueSchema.parse(result),
provenance,
limitations: result.limitations,
locations: [],
});
};
-255
View File
@@ -1,255 +0,0 @@
import { createHash } from "node:crypto";
import { constants, type Stats } from "node:fs";
import { lstat, open } from "node:fs/promises";
import { join } from "node:path";
import type { InspectSignature } from "../domain/native/nativeInspection.js";
import { ticketStructureIssue } from "./NotarizationTicket.js";
/** Notarization tickets are a few kilobytes; larger files are hashed in chunks. */
const HASH_CHUNK_BYTES = 64 * 1024;
/** The code `codesign --verify` should check: the bundle when one was opened. */
export const signedCodePath = (target: {
readonly path: string;
readonly sourcePath?: string;
readonly bundleInfoPlist?: string;
}): string => appBundle(target) ?? target.path;
/**
* The app bundle directory a target was opened from. Only a bundle opened as a
* directory carries its Info.plist; a regular file named `X.app` is not one.
* The bundle is derived from the Info.plist location, not from the outer
* opening path, so an iOS-on-Mac wrapper resolves to the inner `Wrapper/*.app`
* bundle whose executable and ticket were actually inspected.
*/
const appBundle = (target: {
readonly sourcePath?: string;
readonly bundleInfoPlist?: string;
}): string | undefined => {
if (target.bundleInfoPlist === undefined) return undefined;
const derived = bundleDirFromPlist(target.bundleInfoPlist);
if (derived !== undefined) return derived;
return target.sourcePath;
};
/**
* Bundle directory containing an Info.plist: `.../Foo.app/Contents/Info.plist`
* lives two levels below its bundle, while a flat `.../Foo.app/Info.plist`
* lives one level below it.
*/
const bundleDirFromPlist = (plist: string): string | undefined => {
const contentsSuffix = "/Contents/Info.plist";
if (plist.endsWith(contentsSuffix))
return plist.slice(0, -"/Contents/Info.plist".length) || undefined;
const flatSuffix = "/Info.plist";
if (plist.endsWith(flatSuffix))
return plist.slice(0, -"/Info.plist".length) || undefined;
return undefined;
};
/**
* Report a ticket stapled to an app bundle, which `stapler` stores at
* `Contents/CodeResources`. Presence is observed; the ticket's validity and
* Apple's notarization record are not checked, because that needs the network.
*/
export const stapledTicket = async (
target: { readonly sourcePath?: string; readonly bundleInfoPlist?: string },
signal?: AbortSignal,
pathProbe: (path: string, phase: "before" | "after") => Promise<Stats> = (
path,
) => lstat(path),
): Promise<InspectSignature["stapled_ticket"]> => {
signal?.throwIfAborted();
const bundle = appBundle(target);
if (bundle === undefined) {
signal?.throwIfAborted();
return {
status: "not-applicable",
path: null,
sha256: null,
size: null,
reason: null,
};
}
const relative = "Contents/CodeResources";
const path = join(bundle, relative);
try {
signal?.throwIfAborted();
const metadata = await pathProbe(path, "before");
if (!metadata.isFile()) {
signal?.throwIfAborted();
return absent;
}
// Open nonblocking so a concurrent replacement with a FIFO cannot hang
// inspect_signature; the opened handle is revalidated below.
const handle = await open(
path,
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
);
try {
const opened = await handle.stat();
// The path was a regular file at lstat. A directory or FIFO now means
// the ticket was replaced; absence would hide that change.
if (!opened.isFile())
return {
status: "unreadable",
path: relative,
sha256: null,
size: null,
reason: "changed",
};
// If the path was replaced between lstat and open, or mutated while
// hashing, the digest would describe the wrong bytes: dev and ino catch
// replacement, while size and mtime catch same-inode writes. Report any
// drift as changed instead of a stale digest.
if (!sameTicketFile(opened, metadata))
return {
status: "unreadable",
path: relative,
sha256: null,
size: null,
reason: "changed",
};
const structureIssue = await ticketStructureIssue(
async (offset, length) => {
signal?.throwIfAborted();
const buffer = new Uint8Array(length);
let done = 0;
while (done < length) {
const { bytesRead } = await handle.read(
buffer,
done,
length - done,
offset + done,
);
if (bytesRead === 0) break;
done += bytesRead;
}
return buffer.subarray(0, done);
},
opened.size,
);
const hash = createHash("sha256");
const buffer = new Uint8Array(HASH_CHUNK_BYTES);
let size = 0;
while (size < opened.size) {
signal?.throwIfAborted();
const { bytesRead } = await handle.read(
buffer,
0,
Math.min(buffer.length, opened.size - size),
size,
);
if (bytesRead === 0) break;
size += bytesRead;
hash.update(buffer.subarray(0, bytesRead));
}
signal?.throwIfAborted();
const closing = await handle.stat();
if (!sameTicketFile(closing, opened) || size !== opened.size)
return {
status: "unreadable",
path: relative,
sha256: null,
size: null,
reason: "changed",
};
// An atomic replacement swaps the pathname to a new inode while the
// handle still describes the unlinked original: re-resolve the path and
// refuse a digest that no longer belongs to the bundle.
try {
const current = await pathProbe(path, "after");
if (!sameTicketFile(current, opened))
return {
status: "unreadable",
path: relative,
sha256: null,
size: null,
reason: "changed",
};
} catch (cause: unknown) {
signal?.throwIfAborted();
const code = errorCode(cause);
if (code !== "ENOENT" && code !== "ENOTDIR") throw cause;
return {
status: "unreadable",
path: relative,
sha256: null,
size: null,
reason: "changed",
};
}
return {
status: structureIssue === null ? "present" : "unreadable",
path: relative,
sha256: hash.digest("hex"),
size,
reason: structureIssue,
};
} finally {
await handle.close();
}
} catch (cause: unknown) {
const code = errorCode(cause);
if (code === "ENOENT" || code === "ENOTDIR") return absent;
// A privacy or ACL denial leaves the ticket's presence unknown, not the
// whole signature inspection.
if (code === "EACCES" || code === "EPERM" || code === "EIO")
return {
status: "unreadable",
path: relative,
sha256: null,
size: null,
reason: code,
};
throw cause;
}
};
/**
* Whether two observations describe the same file version. Device and inode
* catch replacement; size and mtime catch same-inode writes and truncations
* whose digest would otherwise mix multiple file states.
*/
const sameTicketFile = (
left: {
readonly dev: number;
readonly ino: number;
readonly size: number;
readonly mtimeMs: number;
readonly ctimeMs: number;
},
right: {
readonly dev: number;
readonly ino: number;
readonly size: number;
readonly mtimeMs: number;
readonly ctimeMs: number;
},
): boolean =>
left.dev === right.dev &&
left.ino === right.ino &&
left.size === right.size &&
left.mtimeMs === right.mtimeMs &&
left.ctimeMs === right.ctimeMs;
const absent = {
status: "absent",
path: null,
sha256: null,
size: null,
reason: null,
} as const;
const errorCode = (cause: unknown): string | undefined =>
cause instanceof Error && "code" in cause && typeof cause.code === "string"
? cause.code
: undefined;
/** Limitations that keep verification and notarization claims bounded. */
export const SIGNATURE_POSTURE_LIMITATIONS = [
"Signature verification is local `codesign --verify --deep --strict`; certificate revocation, Gatekeeper policy, and Apple's notarization records are not checked.",
"Security facets are derived from CodeDirectory flags and entitlements; runtime policy such as System Integrity Protection, AMFI, and setuid bits can further restrict a process.",
"Ticket presence requires recognized local s8ch/g8tk container and DER framing; certificate authenticity, ticket signature validity, and ticket-to-code binding are not verified.",
];
-148
View File
@@ -1,148 +0,0 @@
import type { BinaryTarget } from "../domain/binaryTarget.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { canonicalJson } from "../domain/comparisonSemantics.js";
import { ok, type Result } from "../domain/result.js";
import type { NativeCommandCapture } from "./CommandRunner.js";
import { codesignReasons } from "./CodesignVerification.js";
import { parseCodeSignature } from "./parsers/codesign.js";
import { parseSignatureEntitlements } from "./NativeSignatureEntitlements.js";
import {
signatureArchitectures,
summarizeSignatureSlices,
} from "./NativeSignatureSlices.js";
/** The provider owns process execution and typed failure translation. */
export type SignatureCapture = (
argv: readonly string[],
signal?: AbortSignal,
) => Promise<Result<NativeCommandCapture, AnalysisError>>;
/** Detect explicit unsigned display reasons, not words embedded in echoed pathnames. */
export const unsignedSignatureCapture = (
capture: NativeCommandCapture,
path: string,
): boolean =>
capture.exitCode !== null &&
capture.exitCode !== 0 &&
codesignReasons(capture, path).some((reason) =>
/^(?:code object is not signed at all|code object is not signed|not signed at all)/iu.test(
reason,
),
);
/** Slice observations and aggregate knowledge, with every contributing capture retained. */
export interface SignatureSliceObservation {
readonly mixed: boolean;
readonly captures: readonly NativeCommandCapture[];
readonly limitations: readonly string[];
readonly signed: boolean | undefined;
readonly classificationUnknown: boolean;
}
/** Proactively inspect independent signatures of universal Mach-O architectures. */
export const inspectSignatureSlices = async (
target: BinaryTarget,
input: {
readonly format: string | null;
readonly requirements: NativeCommandCapture;
readonly entitlements: NativeCommandCapture;
readonly unsigned: boolean;
},
capture: SignatureCapture,
signal?: AbortSignal,
): Promise<Result<SignatureSliceObservation, AnalysisError>> => {
const architectures = signatureArchitectures(input.format, target);
const gate =
!input.unsigned &&
(unsignedSignatureCapture(input.requirements, target.path) ||
unsignedSignatureCapture(input.entitlements, target.path));
if (!gate && architectures.length <= 1)
return ok({
mixed: false,
captures: [],
limitations: [],
signed: undefined,
classificationUnknown: false,
});
const captures: NativeCommandCapture[] = [];
const signed: string[] = [];
const unsigned: string[] = [];
const unclassified: string[] = [];
const postures = new Map<string, string>();
for (const architecture of architectures) {
const display = await capture(
["-d", "-a", architecture, "--verbose=4", target.path],
signal,
);
if (!display.ok) return display;
captures.push(display.value);
if (display.value.exitCode !== 0) {
(unsignedSignatureCapture(display.value, target.path)
? unsigned
: unclassified
).push(architecture);
continue;
}
signed.push(architecture);
const entitlements = await capture(
["-d", "--entitlements", ":-", "-a", architecture, target.path],
signal,
);
if (!entitlements.ok) return entitlements;
captures.push(entitlements.value);
const directory = parseCodeSignature(display.value.stderr, false, [
target.path,
]).code_directory;
if (
directory?.flags === null ||
directory === null ||
entitlements.value.exitCode !== 0
) {
unclassified.push(architecture);
continue;
}
postures.set(
architecture,
canonicalJson(
{
flags: directory.flags.value,
platform: directory.platform_identifier,
entitlements: parseSignatureEntitlements(entitlements.value.stdout)
.value,
},
"Signature slice posture",
),
);
}
const summary = summarizeSignatureSlices({
signed,
unsigned,
unclassified,
postures,
});
const limitations: string[] = [];
if (unsigned.length > 0)
limitations.push(`Unsigned Mach-O slices: ${unsigned.join(", ")}.`);
if (summary.postureDiffers)
limitations.push(
"Signed Mach-O slices differ in CodeDirectory flags or entitlements; aggregate facets are unknown.",
);
if (unclassified.length > 0)
limitations.push(
`Signature state could not be classified for Mach-O slices: ${unclassified.join(", ")}.`,
);
if (gate && input.requirements.exitCode !== 0)
limitations.push(
"The aggregate designated requirement is unavailable because Mach-O slices have mixed signing states.",
);
if (gate && input.entitlements.exitCode !== 0)
limitations.push(
"The aggregate entitlements are unavailable because Mach-O slices have mixed signing states.",
);
return ok({
...summary,
mixed: gate || summary.mixed,
captures,
limitations,
});
};
-51
View File
@@ -1,51 +0,0 @@
import type { BinaryTarget } from "../domain/binaryTarget.js";
/** Architectures to probe, retaining subtypes from codesign and target inventory. */
export const signatureArchitectures = (
format: string | null,
target: BinaryTarget,
): string[] => {
const universal = /^Mach-O universal \(([^)\r\n]+)\)$/u.exec(
format ?? "",
)?.[1];
const declared =
universal?.split(/\s+/u).filter((name) => name.length > 0) ?? [];
const available =
target.kind === "executable" && target.format === "mach-o"
? target.availableArchitectures.map((name) =>
name === "x86" ? "i386" : name,
)
: [];
return [...new Set([...declared, ...available])];
};
/** Aggregate signing knowledge, keeping inconclusive probes distinct from unsigned. */
export const summarizeSignatureSlices = (input: {
readonly signed: readonly string[];
readonly unsigned: readonly string[];
readonly unclassified: readonly string[];
readonly postures: ReadonlyMap<string, string>;
}): {
readonly signed: boolean | undefined;
readonly mixed: boolean;
readonly postureDiffers: boolean;
readonly classificationUnknown: boolean;
} => {
const classificationUnknown = input.unclassified.length > 0;
const postureDiffers = new Set(input.postures.values()).size > 1;
const signed =
input.signed.length > 0
? true
: classificationUnknown || input.unsigned.length === 0
? undefined
: false;
return {
signed,
classificationUnknown,
postureDiffers,
mixed:
classificationUnknown ||
(input.signed.length > 0 && input.unsigned.length > 0) ||
postureDiffers,
};
};
-39
View File
@@ -1,39 +0,0 @@
import { expect, it } from "vitest";
import { notarizationTicketFixture } from "../../tests/fixtures/notarizationTicket.js";
import { ticketStructureIssue } from "./NotarizationTicket.js";
const inspect = (bytes: Uint8Array) =>
ticketStructureIssue(
async (offset, length) => bytes.subarray(offset, offset + length),
bytes.length,
);
it("recognizes local ticket framing without claiming cryptographic validity", async () => {
expect(await inspect(notarizationTicketFixture())).toBeNull();
});
it("rejects empty, arbitrary, truncated and contradictory ticket containers", async () => {
expect(await inspect(new Uint8Array())).toContain("Not a recognized");
expect(await inspect(Buffer.from("stapled ticket bytes"))).toContain(
"Not a recognized",
);
const ticket = Buffer.from(notarizationTicketFixture());
expect(await inspect(ticket.subarray(0, ticket.length - 1))).toContain(
"signature",
);
ticket.writeUInt32LE(2, 16 + 4 + 8);
expect(await inspect(ticket)).toContain("hash records disagree");
});
it("requires the complete signature field and validates all padding bytes", async () => {
const bytes = Buffer.from(notarizationTicketFixture());
expect(await inspect(bytes.subarray(0, bytes.length - 64))).toContain(
"72 bytes",
);
expect(await inspect(bytes)).toBeNull();
bytes[bytes.length - 1] = 1;
expect(await inspect(bytes)).toContain("signature padding");
expect(await inspect(Buffer.concat([bytes, Buffer.alloc(1)]))).toContain(
"72 bytes",
);
});
-78
View File
@@ -1,78 +0,0 @@
/** Bounded positional reader used to inspect local ticket framing. */
export type TicketReadAt = (
offset: number,
length: number,
) => Promise<Uint8Array>;
/**
* Inspect the local s8ch/g8tk ticket framing. Observed in stapled app tickets;
* see https://www.mothersruin.com/software/Archaeology/reverse/tickets.html.
* This does not authenticate certificates, signatures, or notarized cdhashes.
*/
export const ticketStructureIssue = async (
read: TicketReadAt,
size: number,
): Promise<string | null> => {
const header = Buffer.from(await read(0, 16));
if (header.length !== 16 || header.toString("ascii", 0, 4) !== "s8ch")
return "Not a recognized s8ch notarization ticket container";
if (header.readUInt32LE(4) !== 1)
return `Unsupported notarization ticket container version ${header.readUInt32LE(4)}`;
const certificateSize = header.readUInt32LE(8);
const contentSize = header.readUInt32LE(12);
const contentOffset = 16 + certificateSize;
const signatureOffset = contentOffset + contentSize;
if (certificateSize < 4 || contentSize < 24 || signatureOffset >= size)
return "Ticket certificate, content, or signature extent is missing or truncated";
const content = Buffer.from(await read(contentOffset, 24));
if (content.length !== 24 || content.toString("ascii", 0, 4) !== "g8tk")
return "Ticket content has no complete g8tk header";
const hashSize = content.readUInt16LE(6);
const hashCount = content.readUInt32LE(8);
if (
hashSize === 0 ||
hashCount === 0 ||
24 + (hashSize + 1) * hashCount !== contentSize
)
return "Ticket hash records disagree with the declared content length";
const certificates = await derSequenceExtent(read, 16, certificateSize);
if (certificates !== certificateSize)
return "Ticket certificate block has malformed DER framing";
const signatureFieldSize = 72;
if (size - signatureOffset !== signatureFieldSize)
return "Ticket signature field is truncated or does not contain exactly 72 bytes";
const signatureSize = await derSequenceExtent(
read,
signatureOffset,
signatureFieldSize,
);
if (signatureSize === null || signatureSize < 8)
return "Ticket signature has malformed DER framing";
// The fixed signature field contains DER followed by zero padding.
const paddingSize = size - signatureOffset - signatureSize;
const padding = await read(signatureOffset + signatureSize, paddingSize);
if (padding.byteLength !== paddingSize || padding.some((byte) => byte !== 0))
return "Ticket has malformed signature padding";
return null;
};
/** Read only a DER SEQUENCE tag/length and check its extent against its section. */
const derSequenceExtent = async (
read: TicketReadAt,
offset: number,
available: number,
): Promise<number | null> => {
const prefix = Buffer.from(await read(offset, Math.min(6, available)));
if (prefix.length < 2 || prefix[0] !== 0x30) return null;
const first = prefix[1] ?? 0;
if (first < 128) return first + 2 <= available ? first + 2 : null;
const width = first & 0x7f;
if (width === 0 || width > 4 || prefix.length < width + 2 || prefix[2] === 0)
return null;
let length = 0;
for (let index = 0; index < width; index++)
length = length * 256 + (prefix[index + 2] ?? 0);
return length >= 128 && length + width + 2 <= available
? length + width + 2
: null;
};
-161
View File
@@ -1,161 +0,0 @@
import { createHash } from "node:crypto";
import { constants, type BigIntStats } from "node:fs";
import { lstat, open } from "node:fs/promises";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import {
AnalysisAccessDeniedError,
AnalysisArtifactChangedError,
AnalysisResourceConstraintError,
} from "../domain/analysisErrorCore.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { err, ok, type Result } from "../domain/result.js";
import { NATIVE_MACOS_PROVIDER_IDENTITY } from "./NativeMacOSProviderMetadata.js";
/** Binding of commands to the selected executable's registered content/version. */
export interface SignatureTargetBinding {
readonly identity: string;
}
const identity = (stat: BigIntStats): string =>
[stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].join(":");
const changedTarget = (target: BinaryTarget, reason: string) =>
err(
new AnalysisArtifactChangedError("inspect_signature", target.path, reason),
);
const signatureReadFailure = (
target: BinaryTarget,
cause: unknown,
): AnalysisError => {
const code =
cause instanceof Error && "code" in cause ? cause.code : undefined;
if (code === "EACCES" || code === "EPERM")
return new AnalysisAccessDeniedError(
"inspect_signature",
target.path,
code,
{ cause },
);
if (code === "ENOENT" || code === "ENOTDIR" || code === "ELOOP")
return new AnalysisArtifactChangedError(
"inspect_signature",
target.path,
`Registered signature target is no longer readable (${code}): ${target.path}`,
{ cause },
);
return new ProviderAdapterError(
NATIVE_MACOS_PROVIDER_IDENTITY.id,
"inspect_signature",
{
cause,
diagnostics: {
path: target.path,
phase: "target-version-binding",
system_code: typeof code === "string" ? code : null,
reason: cause instanceof Error ? cause.message : String(cause),
},
},
);
};
/** Establish a bounded-memory digest/version baseline before external commands run. */
export const bindSignatureTarget = async (
target: BinaryTarget,
signal?: AbortSignal,
): Promise<Result<SignatureTargetBinding, AnalysisError>> => {
signal?.throwIfAborted();
try {
const before = await lstat(target.path, { bigint: true });
if (!before.isFile() || before.isSymbolicLink())
return changedTarget(
target,
`Signature target is no longer a regular file: ${target.path}`,
);
const file = await open(
target.path,
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
);
try {
const opened = await file.stat({ bigint: true });
if (identity(opened) !== identity(before))
return changedTarget(
target,
`Signature target changed before open: ${target.path}`,
);
const size = Number(opened.size);
if (!Number.isSafeInteger(size))
return err(
new AnalysisResourceConstraintError(
"inspect_signature",
"file-size",
`Signature target size is not exactly representable: ${target.path}`,
null,
),
);
const hash = createHash("sha256");
const chunk = Buffer.alloc(64 * 1024);
let position = 0;
while (position < size) {
signal?.throwIfAborted();
const { bytesRead } = await file.read(
chunk,
0,
Math.min(chunk.length, size - position),
position,
);
if (bytesRead === 0)
return changedTarget(
target,
`Signature target was truncated while hashing: ${target.path}`,
);
hash.update(chunk.subarray(0, bytesRead));
position += bytesRead;
}
const observed = hash.digest("hex");
if (observed !== target.sha256)
return changedTarget(
target,
`Signature target digest changed: ${target.path}; expected ${target.sha256}, observed ${observed}`,
);
const after = await file.stat({ bigint: true });
const current = await lstat(target.path, { bigint: true });
if (
identity(after) !== identity(opened) ||
identity(current) !== identity(opened)
)
return changedTarget(
target,
`Signature target changed while establishing its version: ${target.path}`,
);
return ok({ identity: identity(opened) });
} finally {
await file.close();
}
} catch (cause: unknown) {
signal?.throwIfAborted();
return err(signatureReadFailure(target, cause));
}
};
/** Reject drift between display, entitlement and verification captures. */
export const verifySignatureTarget = async (
target: BinaryTarget,
binding: SignatureTargetBinding,
signal?: AbortSignal,
): Promise<Result<void, AnalysisError>> => {
signal?.throwIfAborted();
try {
const current = await lstat(target.path, { bigint: true });
return current.isFile() && identity(current) === binding.identity
? ok(undefined)
: changedTarget(
target,
`Signature target changed during inspection: ${target.path}`,
);
} catch (cause: unknown) {
signal?.throwIfAborted();
return err(signatureReadFailure(target, cause));
}
};
-77
View File
@@ -1,77 +0,0 @@
import { describe, expect, it } from "vitest";
import { parseCodeSignature } from "./codesign.js";
const display = (lines: readonly string[]): string =>
[
"Identifier=com.example.fixture",
"Format=app bundle with Mach-O thin (arm64)",
...lines,
"TeamIdentifier=TEAM12345",
"",
].join("\n");
describe("codesign CodeDirectory parsing", () => {
it("decodes CodeDirectory fields and flags from the numeric value", () => {
const parsed = parseCodeSignature(
display([
"CodeDirectory v=20500 size=443 flags=0x12a00(kill,restrict,library-validation,runtime) hashes=3209+7 location=embedded",
"Platform identifier=26",
"Hash type=sha256 size=32",
"Executable Segment flags=0x1",
"Runtime Version=26.4.0",
"Sealed Resources version=2 rules=13 files=290",
]),
false,
);
expect(parsed.code_directory).toEqual({
version: "20500",
flags: {
value: 0x12a00,
names: ["kill", "restrict", "library-validation", "runtime"],
},
code_slots: 3209,
special_slots: 7,
location: "embedded",
hash_type: "sha256",
platform_identifier: 26,
runtime_version: "26.4.0",
executable_segment_flags: 1,
});
expect(parsed.hardened_runtime).toBe(true);
expect(parsed.sealed_resources).toEqual({
status: "sealed",
version: 2,
rules: 13,
files: 290,
});
});
it("reports unsealed, unsigned and incomplete output without guessing", () => {
const bare = parseCodeSignature(
display([
"CodeDirectory v=20400 size=336 location=embedded",
"Sealed Resources=none",
]),
false,
);
expect(bare.code_directory).toMatchObject({
flags: null,
code_slots: null,
platform_identifier: null,
});
expect(bare.sealed_resources.status).toBe("none");
expect(parseCodeSignature(display([]), false)).toMatchObject({
code_directory: null,
sealed_resources: { status: "unknown" },
});
expect(
parseCodeSignature("fixture: code object is not signed at all\n", true),
).toMatchObject({
signed: false,
code_directory: null,
sealed_resources: { status: "none" },
stapled_ticket: { status: "not-applicable" },
});
});
});
-84
View File
@@ -1,5 +1,3 @@
import { type CodeDirectory } from "../../domain/native/codeSigningPosture.js";
import { codeDirectoryFlagNames } from "../CodeSigningPolicy.js";
import {
inspectSignatureSchema,
type InspectSignature,
@@ -25,21 +23,11 @@ export const parseCodeSignature = (
const values = new Map<string, string>();
const authorities: string[] = [];
const cdhashes: string[] = [];
let sealed: InspectSignature["sealed_resources"] = {
status: "unknown",
version: null,
rules: null,
files: null,
};
for (const line of fields.split("\n")) {
if (line.startsWith("CodeDirectory ")) {
values.set("CodeDirectory", line.slice("CodeDirectory ".length));
continue;
}
if (line.startsWith("Sealed Resources")) {
sealed = parseSealedResources(line);
continue;
}
const separator = line.indexOf("=");
if (separator < 1) continue;
const key = line.slice(0, separator).trim();
@@ -60,19 +48,6 @@ export const parseCodeSignature = (
entitlements: null,
timestamp: values.get("Timestamp") ?? null,
hardened_runtime: parseRuntime(values.get("CodeDirectory")),
code_directory: unsigned ? null : parseCodeDirectory(values),
sealed_resources: unsigned
? { status: "none", version: null, rules: null, files: null }
: sealed,
verification: null,
stapled_ticket: {
status: "not-applicable",
path: null,
sha256: null,
size: null,
reason: null,
},
security_facets: [],
limitations: unsigned
? ["Artifact is not signed."]
: [
@@ -129,62 +104,3 @@ const parseRuntime = (value: string | undefined): boolean | null => {
if (flags === undefined) return null;
return flags.split(",").some((flag) => flag.trim() === "runtime");
};
const integerField = (
text: string | undefined,
pattern: RegExp,
radix = 10,
): number | null => {
const match = text === undefined ? undefined : pattern.exec(text)?.[1];
if (match === undefined) return null;
const value = Number.parseInt(match, radix);
return Number.isSafeInteger(value) ? value : null;
};
/**
* `CodeDirectory v=20500 size=… flags=0x10000(runtime) hashes=3209+7
* location=embedded`, plus the separate hash, platform, runtime-version and
* executable-segment lines. Flag names are decoded from the numeric value.
*/
const parseCodeDirectory = (
values: ReadonlyMap<string, string>,
): CodeDirectory | null => {
const line = values.get("CodeDirectory");
if (line === undefined) return null;
const flags = integerField(line, /(?:^|\s)flags=0x([0-9a-f]+)/iu, 16);
return {
version: /(?:^|\s)v=(\S+)/u.exec(line)?.[1] ?? null,
flags:
flags === null
? null
: { value: flags, names: codeDirectoryFlagNames(flags) },
code_slots: integerField(line, /(?:^|\s)hashes=(\d+)\+/u),
special_slots: integerField(line, /(?:^|\s)hashes=\d+\+(\d+)/u),
location: /(?:^|\s)location=(\S+)/u.exec(line)?.[1] ?? null,
hash_type: values.get("Hash type")?.split(/\s+/u)[0] ?? null,
platform_identifier: integerField(
values.get("Platform identifier"),
/^(\d+)$/u,
),
runtime_version: values.get("Runtime Version") ?? null,
executable_segment_flags: integerField(
values.get("Executable Segment flags"),
/^0x([0-9a-f]+)$/iu,
16,
),
};
};
/** `Sealed Resources version=2 rules=13 files=290` or `Sealed Resources=none`. */
const parseSealedResources = (
line: string,
): InspectSignature["sealed_resources"] => {
if (/^Sealed Resources\s*=\s*none$/u.test(line.trim()))
return { status: "none", version: null, rules: null, files: null };
return {
status: "sealed",
version: integerField(line, /\sversion=(\d+)/u),
rules: integerField(line, /\srules=(\d+)/u),
files: integerField(line, /\sfiles=(\d+)/u),
};
};
@@ -1,6 +1,7 @@
import { writeFile } from "node:fs/promises";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createPackageWithOptions } from "@electron/asar";
import { Filter } from "incur";
import { expect } from "vitest";
import { z } from "zod";
@@ -116,3 +117,42 @@ cliTest(
expect(output.json).toEqual({});
},
);
for (const command of ["analyze", "analyze-javascript-application"]) {
cliTest(
`${command} forwards the integrity policy while preserving JSON output`,
async ({ cli }) => {
const root = await createTestTempDirectory("rea-js-cli-integrity-");
const source = join(root, "source");
await mkdir(source);
await writeFile(join(source, "main.js"), "require('./addon.node');\n");
await writeFile(join(source, "addon.node"), "original");
const archive = join(root, "app.asar");
await createPackageWithOptions(source, archive, { unpack: "*.node" });
await writeFile(join(`${archive}.unpacked`, "addon.node"), "changed");
const strict = await cli.run({ arguments: [command, archive, "--json"] });
expect(strict.json).toMatchObject({
code: "artifact_integrity_mismatch",
});
const recorded = await cli.run({
arguments: [
command,
archive,
"--integrity-policy",
"record-and-continue",
"--json",
],
});
expect(recorded.exitCode).toBe(0);
expect(recorded.json).toMatchObject({
parameters: { integrity_policy: "record-and-continue" },
normalized_result: {
integrity_contradictions: [
{ logical_path: "addon.node", trust: "observed-untrusted" },
],
graph: { coverage: { status: "partial" } },
},
});
},
);
}
@@ -0,0 +1,96 @@
import { createHash } from "node:crypto";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createPackage, createPackageWithOptions } from "@electron/asar";
import { expect, it } from "vitest";
import { extractArtifact } from "../../../src/artifacts/extraction/ArtifactExtraction.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it("does not claim unmaterialized nested integrity contradictions were extracted", async () => {
const root = await createTestTempDirectory("rea-nested-integrity-extract-");
const source = join(root, "source");
const original = "console.log('ok');\n";
const changed = "console.log('no');\n";
await mkdir(source);
await writeFile(join(source, "main.js"), original);
const app = join(root, "app");
await mkdir(app);
const archive = join(app, "app.asar");
await createPackage(source, archive);
const bytes = await readFile(archive);
const contentOffset = bytes.indexOf(original);
expect(contentOffset).toBeGreaterThanOrEqual(0);
bytes.write(changed, contentOffset, "utf8");
await writeFile(archive, bytes);
const result = await extractArtifact({
inputPath: app,
// A directory path is read as a directory before this format is consulted.
inputFormat: "zip",
outputRoot: join(root, "out"),
integrity: { mode: "record-and-continue" },
});
expect(result.artifacts.map(({ relative_path }) => relative_path)).toEqual([
"app.asar",
]);
expect(result.integrity_contradictions).toEqual([
expect.objectContaining({
logical_path: "app.asar/main.js",
declared_sha256: createHash("sha256").update(original).digest("hex"),
observed_sha256: createHash("sha256").update(changed).digest("hex"),
trust: "observed-untrusted",
}),
]);
expect(result.limitations.join("\n")).toContain(
"were not written as their own files",
);
expect(result.limitations.join("\n")).toContain("main.js");
expect(result.limitations.join("\n")).not.toContain(
"extracted file(s) contradict",
);
});
it.each(["addon.node", "lib/addon.node"])(
"recognizes unpacked companion %s materialized under its filesystem path",
async (member) => {
const root = await createTestTempDirectory(
"rea-unpacked-integrity-extract-",
);
const source = join(root, "source");
const app = join(root, "app");
await mkdir(source);
await mkdir(app);
const original = "unsigned addon bytes";
const observed = "signed addon bytes";
await mkdir(join(source, "lib"));
await writeFile(join(source, member), original);
const archive = join(app, "app.asar");
await createPackageWithOptions(source, archive, { unpack: "**/*.node" });
await writeFile(join(`${archive}.unpacked`, member), observed);
const output = join(root, "out");
const result = await extractArtifact({
inputPath: app,
inputFormat: "zip",
outputRoot: output,
integrity: { mode: "record-and-continue" },
});
expect(
await readFile(join(output, `app.asar.unpacked/${member}`), "utf8"),
).toBe(observed);
expect(result.integrity_contradictions).toEqual([
expect.objectContaining({
logical_path: `app.asar/${member}`,
unpacked: true,
}),
]);
expect(result.limitations.join("\n")).toContain(
"1 extracted file(s) contradict declared integrity",
);
expect(result.limitations.join("\n")).not.toContain(
"were not written as their own files",
);
},
);
+80 -4
View File
@@ -66,8 +66,7 @@ it.each([
error: {
code: "artifact_integrity_mismatch",
category: "integrity_mismatch",
message:
"Artifact is invalid or has changed. Get a fresh copy and try again.",
message: INTEGRITY_REMEDIATION,
details: {
logical_path: "main.js",
declared_sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
@@ -76,8 +75,7 @@ it.each([
},
retryable: false,
remediation: {
action:
"Artifact is invalid or has changed. Get a fresh copy and try again.",
action: INTEGRITY_REMEDIATION,
},
},
});
@@ -92,6 +90,9 @@ it.each([
20_000,
);
const INTEGRITY_REMEDIATION =
"Artifact bytes contradict their declared integrity. If that is expected, such as an unpacked native module signed after packaging, rerun with the record-and-continue integrity policy (integrity_policy in MCP, --integrity-policy on the CLI) to keep the mismatch as an untrusted contradiction; otherwise get a fresh copy.";
const artifactInventoryResultSchema = z.object({
occurrences: z.array(
z.object({ logical_path: z.string(), hash_status: z.string() }),
@@ -148,6 +149,81 @@ it("extracts an active archive through MCP when requested", async () => {
}
});
it("extracts an unpacked integrity mismatch only when the caller records it", async () => {
const root = await createTestTempDirectory("rea-asar-extract-continue-mcp-");
const source = join(root, "source");
await mkdir(source);
await writeFile(join(source, "main.js"), "console.log('ok');\n");
await writeFile(join(source, "kept.txt"), "kept\n");
const archive = join(root, "fixture.asar");
await createPackageWithOptions(source, archive, { unpack: "*.js" });
// Code signing after packaging changes unpacked bytes in the same way.
await writeFile(
join(`${archive}.unpacked`, "main.js"),
"console.log('no');\n",
);
const session = createTestBinarySession(new ArtifactProvider());
const server = createServer(session, session);
const client = new Client({ name: "asar-extract-continue", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
let outputRoot: string | undefined;
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
await client.callTool({
name: "open_binary",
arguments: { path: archive },
});
const strict = await client.callTool({
name: "extract_artifact",
arguments: {},
});
expect(strict.isError).toBe(true);
expect(strict.structuredContent).toMatchObject({
error: {
code: "artifact_integrity_mismatch",
message: INTEGRITY_REMEDIATION,
},
});
const result = await client.callTool({
name: "extract_artifact",
arguments: { integrity_policy: "record-and-continue" },
});
expect(result.isError, JSON.stringify(result.structuredContent)).not.toBe(
true,
);
const extraction = z
.object({
output_root: z.string(),
integrity_contradictions:
artifactInventoryResultSchema.shape.integrity_contradictions,
limitations: z.array(z.string()),
})
.parse(compactResult(result.structuredContent).result);
outputRoot = extraction.output_root;
expect(await readFile(join(outputRoot, "main.js"), "utf8")).toBe(
"console.log('no');\n",
);
expect(await readFile(join(outputRoot, "kept.txt"), "utf8")).toBe("kept\n");
expect(extraction.integrity_contradictions).toEqual([
expect.objectContaining({
logical_path: "main.js",
trust: "observed-untrusted",
}),
]);
expect(extraction.limitations).toContain(
"1 extracted file(s) contradict declared integrity; their observed bytes were written and are untrusted.",
);
} finally {
await Promise.allSettled([client.close(), server.close(), session.close()]);
if (outputRoot !== undefined)
await rm(outputRoot, { recursive: true, force: true });
}
});
it("extracts a macOS app bundle through MCP", async () => {
const root = await createTestTempDirectory("rea-artifact-extract-app-mcp-");
const contents = join(root, "Fixture.app", "Contents");
@@ -1,140 +0,0 @@
import { expect, it } from "vitest";
import { signatureVerification } from "../../../../src/native/CodesignVerification.js";
import { NativeFixtureRunner } from "../../../fixtures/nativeCommands.js";
it.each(["permission denied", "I/O error", "EACCES"])(
"does not classify echoed pathname %s as an I/O failure",
async (text) => {
const path = `/Applications/${text}.app`;
const capture = await new NativeFixtureRunner().run("codesign", [
"--verify",
path,
]);
if (!capture.ok) throw capture.error;
const observed = signatureVerification(
{
...capture.value,
exitCode: 1,
stderr: `${path}: a sealed resource is missing or invalid\n`,
},
path,
false,
);
expect(observed.status).toBe("invalid");
expect(observed.diagnostics).toEqual([
`${path}: a sealed resource is missing or invalid`,
]);
},
);
it("keeps operational, unsigned, definite invalid and unrecognized failures distinct", async () => {
const path = "/Applications/Fixture.app";
const capture = await new NativeFixtureRunner().run("codesign", [
"--verify",
path,
]);
if (!capture.ok) throw capture.error;
const status = (reason: string, unsigned = false) =>
signatureVerification(
{ ...capture.value, exitCode: 1, stderr: `${path}: ${reason}\n` },
path,
unsigned,
).status;
expect(status("permission denied")).toBe("unknown");
expect(status("I/O error")).toBe("unknown");
expect(status("invalid signature")).toBe("invalid");
expect(status("main executable failed strict validation")).toBe("invalid");
expect(status("bundle format unrecognized, invalid, or unsuitable")).toBe(
"invalid",
);
expect(
status(
"resource fork, Finder information, or similar detritus not allowed",
),
).toBe("invalid");
expect(status("code object is not signed at all", true)).toBe("unsigned");
expect(status("code object is not signed at all")).toBe("invalid");
expect(status("unrecognized failure")).toBe("unknown");
});
it("excludes complete selected paths with embedded newlines before classifying reasons", async () => {
const path =
"/Applications/permission denied\ncode object is not signed at all\nFixture.app";
const capture = await new NativeFixtureRunner().run("codesign", [
"--verify",
path,
]);
if (!capture.ok) throw capture.error;
const result = signatureVerification(
{ ...capture.value, exitCode: 1, stderr: `${path}: invalid signature\n` },
path,
false,
);
expect(result.status).toBe("invalid");
expect(result.diagnostics.join("\n")).toContain(path);
});
it("preserves definitive invalidity when other components have operational failures", async () => {
const path = "/Applications/Fixture.app";
const capture = await new NativeFixtureRunner().run("codesign", [
"--verify",
path,
]);
if (!capture.ok) throw capture.error;
const observed = signatureVerification(
{
...capture.value,
exitCode: 1,
stderr: `${path}/Contents/Helpers/one: permission denied\n${path}/Contents/Helpers/two: invalid signature\n`,
},
path,
false,
);
expect(observed.status).toBe("invalid");
expect(observed.diagnostics).toHaveLength(2);
});
it("preserves unmatched prepared records and ignores unprefixed nested-name fragments as reasons", async () => {
const path = "/Applications/Fixture.app";
const capture = await new NativeFixtureRunner().run("codesign", [
"--verify",
path,
]);
if (!capture.ok) throw capture.error;
const stderr = `--prepared:${path}/Contents/Helpers/odd\ninvalid signature\n${path}: permission denied\n`;
const result = signatureVerification(
{ ...capture.value, exitCode: 1, stderr },
path,
false,
);
expect(result.status).toBe("unknown");
expect(result.prepared_nested_code).toEqual([`${path}/Contents/Helpers/odd`]);
expect(result.raw_stderr).toBe(stderr);
expect(result.diagnostics).toContain("invalid signature");
});
it("keeps failed verification unknown when nested progress can contain a selected-path diagnostic", async () => {
const path = "/Applications/Fixture.app";
const capture = await new NativeFixtureRunner().run("codesign", [
"--verify",
path,
]);
if (!capture.ok) throw capture.error;
const stderr = `--prepared:${path}/Contents/Helpers/odd\n${path}: invalid signature\n${path}: permission denied\n`;
const result = signatureVerification(
{ ...capture.value, exitCode: 1, stderr },
path,
false,
"ambiguous",
);
expect(result.status).toBe("unknown");
expect(result.raw_stderr).toBe(stderr);
expect(
signatureVerification(
{ ...capture.value, exitCode: 0, stderr },
path,
false,
"ambiguous",
).status,
).toBe("valid");
});
@@ -1,4 +1,3 @@
import { createHash } from "node:crypto";
import { mkdir, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -19,14 +18,9 @@ import { parseCodeSignature } from "../../../../src/native/parsers/codesign.js";
import {
NativeFixtureRunner as FixtureRunner,
nativeFixture as fixture,
nativeMachoTarget as unboundMachoTarget,
nativeMachoTarget as machoTarget,
} from "../../../fixtures/nativeCommands.js";
const machoTarget = (path: string, app?: string) => ({
...unboundMachoTarget(path, app),
sha256: createHash("sha256").update("fixture").digest("hex"),
});
let directory: string | undefined;
afterEach(async () => {
if (directory !== undefined)
@@ -324,13 +318,10 @@ class PrototypeEntitlementsRunner extends FixtureRunner {
describe("native signature entitlements", () => {
it("reports entitlement entries keyed __proto__ that the result omits", async () => {
directory = await createTestTempDirectory("rea-signature-entitlements-");
const executable = join(directory, "fixture");
await writeFile(executable, "fixture");
const client = new NativeMacOSProvider(
new PrototypeEntitlementsRunner(),
"darwin",
).createClient(machoTarget(executable));
).createClient(machoTarget("/private/fixture"));
const signature = await client.execute("inspect_signature", {});
@@ -1,985 +0,0 @@
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
import { createHash } from "node:crypto";
import { chmod, lstat, mkdir, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { NativeMacOSProvider } from "../../../../src/native/NativeMacOSProvider.js";
import { stapledTicket } from "../../../../src/native/NativeSignaturePosture.js";
import { AnalysisCancelledError } from "../../../../src/domain/analysisErrorCore.js";
import { ok } from "../../../../src/domain/result.js";
import { inspectSignatureSchema } from "../../../../src/domain/native/nativeInspection.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { notarizationTicketFixture } from "../../../fixtures/notarizationTicket.js";
import {
NativeFixtureRunner as FixtureRunner,
nativeMachoTarget as unboundMachoTarget,
} from "../../../fixtures/nativeCommands.js";
const machoTarget = (path: string, app?: string) => ({
...unboundMachoTarget(path, app),
sha256: createHash("sha256").update("fixture").digest("hex"),
});
const TAMPERED_STDERR =
"--prepared:/Applications/Fixture.app/Contents/XPCServices/B.xpc\n--validated:/Applications/Fixture.app/Contents/XPCServices/B.xpc\n--validated:/Applications/Fixture.app/Contents/PlugIns/A.appex\n/Applications/Fixture.app: a sealed resource is missing or invalid\nfile modified: /Applications/Fixture.app/Contents/Resources/en.lproj/Main.nib\n";
/** Fail only strict verification, as a tampered bundle does. */
class TamperedRunner extends FixtureRunner {
override async run(tool: string, arguments_: readonly string[]) {
const result = await super.run(tool, arguments_);
if (!result.ok || arguments_[0] !== "--verify") return result;
const stderr = TAMPERED_STDERR.replaceAll(
"/Applications/Fixture.app",
arguments_.at(-1) ?? "",
);
return ok({
...result.value,
stdout: "",
stderr,
stdoutBytes: 0,
stderrBytes: Buffer.byteLength(stderr),
exitCode: 1,
});
}
}
const fixtureApp = async (ticket: string | Uint8Array | undefined) => {
const directory = await createTestTempDirectory("rea-signature-posture-");
const app = join(directory, "Fixture.app");
const executable = join(app, "Contents/MacOS/Fixture");
await mkdir(join(app, "Contents/MacOS"), { recursive: true });
await writeFile(executable, "fixture");
if (ticket !== undefined)
await writeFile(join(app, "Contents/CodeResources"), ticket);
return { app, executable };
};
describe("native signature posture", () => {
it("verifies the opened bundle and reports a stapled ticket", async () => {
const ticket = notarizationTicketFixture();
const { app, executable } = await fixtureApp(ticket);
const signature = await new NativeMacOSProvider(
new FixtureRunner(),
"darwin",
)
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
expect(signature.ok).toBe(true);
if (!signature.ok) return;
const result = inspectSignatureSchema.parse(signature.value.result);
expect(result.code_directory).toMatchObject({
version: "20500",
flags: { value: 0x10000, names: ["runtime"] },
code_slots: 10,
special_slots: 7,
});
expect(result.verification).toMatchObject({
path: app,
status: "valid",
exit_code: 0,
});
expect(result.stapled_ticket).toEqual({
status: "present",
path: "Contents/CodeResources",
sha256: createHash("sha256").update(ticket).digest("hex"),
size: ticket.length,
reason: null,
});
expect(
Object.fromEntries(
result.security_facets.map(({ facet, state }) => [facet, state]),
),
).toEqual({
"library-validation": "enforced",
"dyld-environment-variables": "ignored",
"debugger-attach": "blocked",
"executable-memory": "restricted",
"app-sandbox": "sandboxed",
});
expect(result.provenance.map(({ command }) => command[1])).toContain(
"--verify",
);
});
it("keeps a failed strict verification as an observation", async () => {
const { app, executable } = await fixtureApp(undefined);
await mkdir(join(app, "Contents/PlugIns/A.appex"), { recursive: true });
await mkdir(join(app, "Contents/XPCServices/B.xpc"), { recursive: true });
const signature = await new NativeMacOSProvider(
new TamperedRunner(),
"darwin",
)
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
expect(signature.ok).toBe(true);
if (!signature.ok) return;
const result = inspectSignatureSchema.parse(signature.value.result);
expect(result.verification).toMatchObject({
path: app,
status: "invalid",
exit_code: 1,
diagnostics: [
`${app}: a sealed resource is missing or invalid`,
`file modified: ${app}/Contents/Resources/en.lproj/Main.nib`,
],
validated_nested_code: [
`${app}/Contents/PlugIns/A.appex`,
`${app}/Contents/XPCServices/B.xpc`,
],
});
expect(result.stapled_ticket.status).toBe("absent");
});
it("does not look for a stapled ticket beside a bare Mach-O", async () => {
const directory = await createTestTempDirectory("rea-signature-bare-");
const executable = join(directory, "tool");
await writeFile(executable, "fixture");
const signature = await new NativeMacOSProvider(
new FixtureRunner(),
"darwin",
)
.createClient(machoTarget(executable))
.execute("inspect_signature", {});
expect(signature.ok && signature.value.result).toMatchObject({
verification: { path: executable },
stapled_ticket: { status: "not-applicable" },
});
});
it.skipIf(process.getuid?.() === 0)(
"keeps inspecting when the stapled ticket cannot be read",
async () => {
const { app, executable } = await fixtureApp("ticket");
const ticket = join(app, "Contents/CodeResources");
await chmod(ticket, 0o000);
try {
const signature = await new NativeMacOSProvider(
new FixtureRunner(),
"darwin",
)
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
expect(signature.ok && signature.value.result).toMatchObject({
stapled_ticket: {
status: "unreadable",
path: "Contents/CodeResources",
sha256: null,
reason: "EACCES",
},
verification: { status: "valid" },
});
} finally {
await chmod(ticket, 0o644);
}
},
);
it("reports unsigned nested code inside a signed bundle as invalid", async () => {
const { app, executable } = await fixtureApp(undefined);
const signature = await new NativeMacOSProvider(
new UnsignedNestedRunner(),
"darwin",
)
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
expect(signature.ok && signature.value.result).toMatchObject({
signed: true,
verification: { status: "invalid", exit_code: 1 },
});
});
});
describe("native signature posture boundaries", () => {
it("verifies the inner bundle for iOS-on-Mac wrappers", async () => {
const directory = await createTestTempDirectory("rea-signature-wrapper-");
const outer = join(directory, "WrapperApp.app");
const inner = join(outer, "Wrapper", "Inner.app");
const executable = join(inner, "Contents/MacOS/Tool");
await mkdir(join(inner, "Contents/MacOS"), { recursive: true });
await writeFile(executable, "fixture");
const target = {
...machoTarget(executable),
sourcePath: outer,
bundleInfoPlist: join(inner, "Contents/Info.plist"),
};
const signature = await new NativeMacOSProvider(
new FixtureRunner(),
"darwin",
)
.createClient(target)
.execute("inspect_signature", {});
expect(signature.ok && signature.value.result).toMatchObject({
verification: { path: inner },
});
});
it("treats a regular file named .app as a bare Mach-O", async () => {
const directory = await createTestTempDirectory("rea-signature-file-");
const executable = join(directory, "Tool.app");
await writeFile(executable, "fixture");
const signature = await new NativeMacOSProvider(
new FixtureRunner(),
"darwin",
)
.createClient({ ...machoTarget(executable), sourcePath: executable })
.execute("inspect_signature", {});
expect(signature.ok && signature.value.result).toMatchObject({
verification: { path: executable },
stapled_ticket: { status: "not-applicable" },
});
});
it("applies platform policy only after the signature satisfies anchor apple", async () => {
const { app, executable } = await fixtureApp(undefined);
const facets = async (anchorExit: number) => {
const signature = await new NativeMacOSProvider(
new PlatformRunner(anchorExit),
"darwin",
)
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
if (!signature.ok) throw signature.error;
const result = inspectSignatureSchema.parse(signature.value.result);
expect(result.provenance.map(({ command }) => command.at(-2))).toContain(
"-R=anchor apple",
);
if (anchorExit === 0)
expect(
result.limitations.some((line) =>
line.startsWith("Apple-origin check failed"),
),
).toBe(false);
else
expect(result.limitations).toContain(
"Apple-origin check failed: code failed to satisfy specified code requirement(s)",
);
return Object.fromEntries(
result.security_facets.map(({ facet, state }) => [facet, state]),
);
};
expect(await facets(0)).toMatchObject({
"library-validation": "enforced",
"dyld-environment-variables": "ignored",
"debugger-attach": "blocked",
});
expect(await facets(3)).toMatchObject({
"library-validation": "unknown",
"dyld-environment-variables": "unknown",
"debugger-attach": "unknown",
});
});
it("flags reported nested code that does not exist as a split path", async () => {
const { app, executable } = await fixtureApp(undefined);
const signature = await new NativeMacOSProvider(
new NewlinePathRunner(),
"darwin",
)
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
if (!signature.ok) throw signature.error;
const result = inspectSignatureSchema.parse(signature.value.result);
// The line projection splits the name; the fragment is flagged.
expect(result.verification?.validated_nested_code).toEqual([
`${app}/Contents/Helpers/odd`,
]);
expect(result.limitations).toContainEqual(
expect.stringContaining(
`validated nested code at ${JSON.stringify(`${app}/Contents/Helpers/odd`)}, which does not exist`,
),
);
});
it("reports cancellation while hashing the stapled ticket", async () => {
const { app, executable } = await fixtureApp("ticket");
const controller = new AbortController();
const signature = await new NativeMacOSProvider(
new AbortAfterVerifyRunner(controller),
"darwin",
)
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {}, { signal: controller.signal });
expect(signature.ok).toBe(false);
if (signature.ok) return;
expect(signature.error).toBeInstanceOf(AnalysisCancelledError);
});
});
describe("native signature posture slice-aware cases", () => {
it("keeps main-executable facets when only nested code fails", async () => {
const { app, executable } = await fixtureApp(undefined);
const signature = await new NativeMacOSProvider(
new NestedOnlyFailureRunner(app),
"darwin",
)
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
if (!signature.ok) throw signature.error;
const result = inspectSignatureSchema.parse(signature.value.result);
expect(result.verification?.status).toBe("invalid");
expect(
result.security_facets.find(({ facet }) => facet === "library-validation")
?.state,
).toBe("enforced");
});
it("probes every slice of a universal binary before declaring it signed", async () => {
const { app, executable } = await fixtureApp(undefined);
const signature = await new NativeMacOSProvider(
new UniversalMixedRunner(),
"darwin",
)
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
if (!signature.ok) throw signature.error;
const result = inspectSignatureSchema.parse(signature.value.result);
// Aggregate display calls report the signed native slice; the unsigned
// x86_64 slice is found only per-architecture.
expect(result.verification?.status).toBe("valid");
expect(
result.security_facets.find(
({ facet }) => facet === "library-validation",
),
).toMatchObject({
state: "unknown",
evidence: ["architecture slices differ in signing state"],
});
expect(result.limitations).toContainEqual(
expect.stringContaining("Unsigned Mach-O slices: x86_64."),
);
});
it("preserves a trailing carriage return in reported nested paths", async () => {
const { app, executable } = await fixtureApp(undefined);
const signature = await new NativeMacOSProvider(
new CarriageReturnPathRunner(),
"darwin",
)
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
if (!signature.ok) throw signature.error;
const result = inspectSignatureSchema.parse(signature.value.result);
// The CR is a valid pathname byte, not a line delimiter: it is kept and
// the nonexistent path is flagged rather than silently normalized.
expect(result.verification?.validated_nested_code).toEqual([
`${app}/Contents/Helpers/cr\r`,
]);
expect(result.limitations).toContainEqual(
expect.stringContaining("which does not exist"),
);
});
it("marks facets unknown when signed slices differ in posture", async () => {
const { app, executable } = await fixtureApp(undefined);
const signature = await new NativeMacOSProvider(
new UniversalPostureDiffRunner(),
"darwin",
)
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
if (!signature.ok) throw signature.error;
const result = inspectSignatureSchema.parse(signature.value.result);
// Every slice verifies, but their CodeDirectory flags disagree.
expect(result.verification?.status).toBe("valid");
expect(
result.security_facets.find(
({ facet }) => facet === "library-validation",
),
).toMatchObject({
state: "unknown",
evidence: ["architecture slices differ in signing state"],
});
expect(result.limitations).toContainEqual(
expect.stringContaining("differ in CodeDirectory flags or entitlements"),
);
});
it("reports verification I/O failures as unknown, not invalid", async () => {
const { app, executable } = await fixtureApp(undefined);
const signature = await new NativeMacOSProvider(
new PermissionDeniedRunner(),
"darwin",
)
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
if (!signature.ok) throw signature.error;
const result = inspectSignatureSchema.parse(signature.value.result);
expect(result.verification?.status).toBe("unknown");
expect(result.limitations).toContainEqual(
expect.stringContaining("not a proven broken signature"),
);
});
});
describe("signature architecture coverage", () => {
it("does not let uncertain display probes hide definitive verification failure", async () => {
const { app, executable } = await fixtureApp(undefined);
const signature = await new NativeMacOSProvider(
new DefiniteInvalidWithUncertainSlicesRunner(),
"darwin",
)
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
if (!signature.ok) throw signature.error;
const result = inspectSignatureSchema.parse(signature.value.result);
expect(result.signed).toBe(true);
expect(result.verification?.status).toBe("invalid");
expect(result.limitations).toContainEqual(
expect.stringContaining("could not be classified"),
);
});
it("does not turn inconclusive slice probes into an unsigned claim", async () => {
const { app, executable } = await fixtureApp(undefined);
const signature = await new NativeMacOSProvider(
new InconclusiveSlicesRunner(),
"darwin",
)
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
if (!signature.ok) throw signature.error;
const result = inspectSignatureSchema.parse(signature.value.result);
expect(result.signed).toBe(true);
expect(result.verification?.status).toBe("unknown");
expect(
result.security_facets.every(({ state }) => state === "unknown"),
).toBe(true);
expect(result.limitations).toContainEqual(
expect.stringContaining("could not be classified"),
);
});
it("does not report arbitrary ticket-location bytes as a stapled ticket", async () => {
const bytes = "stapled ticket bytes";
const { app, executable } = await fixtureApp(bytes);
const signature = await new NativeMacOSProvider(
new FixtureRunner(),
"darwin",
)
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
if (!signature.ok) throw signature.error;
const result = inspectSignatureSchema.parse(signature.value.result);
expect(result.stapled_ticket).toMatchObject({
status: "unreadable",
sha256: createHash("sha256").update(bytes).digest("hex"),
size: bytes.length,
reason: "Not a recognized s8ch notarization ticket container",
});
});
it("probes a valid x86_64h subtype rather than dropping it", async () => {
const { app, executable } = await fixtureApp(undefined);
const signature = await new NativeMacOSProvider(
new UniversalMixedRunner("x86_64h"),
"darwin",
)
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
if (!signature.ok) throw signature.error;
const result = inspectSignatureSchema.parse(signature.value.result);
expect(result.limitations).toContain("Unsigned Mach-O slices: x86_64h.");
expect(
result.security_facets.every(({ state }) => state === "unknown"),
).toBe(true);
});
it("retains per-slice entitlement captures used to compare posture", async () => {
const { app, executable } = await fixtureApp(undefined);
const signature = await new NativeMacOSProvider(
new UniversalPostureDiffRunner(),
"darwin",
)
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
if (!signature.ok) throw signature.error;
const result = inspectSignatureSchema.parse(signature.value.result);
const commands = result.provenance.filter(
({ command }) =>
command.includes("-a") && command.includes("--entitlements"),
);
expect(commands).toHaveLength(2);
expect(result.entitlements).toEqual({
"com.apple.security.app-sandbox": true,
});
});
});
describe("signature target version binding", () => {
it("rejects a replacement before invoking signature tools", async () => {
const { app, executable } = await fixtureApp(undefined);
const runner = new (class extends FixtureRunner {
calls = 0;
override async run(tool: string, args: readonly string[]) {
this.calls += 1;
return super.run(tool, args);
}
})();
const client = new NativeMacOSProvider(runner, "darwin").createClient(
machoTarget(executable, app),
);
await writeFile(executable, "replacement bytes");
const signature = await client.execute("inspect_signature", {});
expect(signature.ok).toBe(false);
if (signature.ok) throw new Error("Expected target change");
expect(projectAnalysisError(signature.error)).toMatchObject({
code: "artifact_changed",
details: { path: executable },
});
expect(runner.calls).toBe(0);
});
it.skipIf(process.getuid?.() === 0)(
"rejects an unreadable selected executable",
async () => {
const { app, executable } = await fixtureApp(undefined);
const client = new NativeMacOSProvider(
new FixtureRunner(),
"darwin",
).createClient(machoTarget(executable, app));
await chmod(executable, 0);
try {
const signature = await client.execute("inspect_signature", {});
expect(signature.ok).toBe(false);
if (signature.ok) throw new Error("Expected access denial");
expect(projectAnalysisError(signature.error)).toMatchObject({
code: "access_denied",
details: { path: executable },
});
} finally {
await chmod(executable, 0o600);
}
},
);
it("reports a regular ticket replaced by a directory as changed", async () => {
const { app } = await fixtureApp(notarizationTicketFixture());
const ticket = await stapledTicket(
{ sourcePath: app, bundleInfoPlist: join(app, "Contents/Info.plist") },
undefined,
async (path, phase) => {
const metadata = await lstat(path);
if (phase === "before") {
await rm(path);
await mkdir(path);
}
return metadata;
},
);
expect(ticket).toMatchObject({
status: "unreadable",
path: "Contents/CodeResources",
reason: "changed",
sha256: null,
});
});
it.each(["EACCES", "EPERM", "EIO"])(
"preserves final ticket-path failure %s instead of inventing mutation",
async (code) => {
const { app } = await fixtureApp(notarizationTicketFixture());
const ticket = await stapledTicket(
{ sourcePath: app, bundleInfoPlist: join(app, "Contents/Info.plist") },
undefined,
async (path, phase) => {
if (phase === "after")
throw Object.assign(new Error("host lookup failed"), { code });
return lstat(path);
},
);
expect(ticket).toMatchObject({
status: "unreadable",
reason: code,
sha256: null,
});
},
);
it("rejects observations when the executable changes between captures", async () => {
const { app, executable } = await fixtureApp(undefined);
const signature = await new NativeMacOSProvider(
new ReplacingExecutableRunner(),
"darwin",
)
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
expect(signature.ok).toBe(false);
if (signature.ok) throw new Error("Expected target change");
expect(projectAnalysisError(signature.error)).toMatchObject({
code: "artifact_changed",
details: { path: executable },
});
});
it.skipIf(process.getuid?.() === 0)(
"reports denied nested-path completeness checks",
async () => {
const { app, executable } = await fixtureApp(undefined);
const helpers = join(app, "Contents/Helpers");
await mkdir(helpers);
await chmod(helpers, 0);
try {
const signature = await new NativeMacOSProvider(
new (class extends FixtureRunner {
override async run(tool: string, args: readonly string[]) {
const result = await super.run(tool, args);
if (!result.ok || args[0] !== "--verify") return result;
const stderr = `--prepared:${helpers}/odd\n${app}: invalid signature\n${app}: permission denied\n`;
return ok({
...result.value,
exitCode: 1,
stderr,
stderrBytes: Buffer.byteLength(stderr),
});
}
})(),
"darwin",
)
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
if (!signature.ok) throw signature.error;
const result = inspectSignatureSchema.parse(signature.value.result);
expect(result.verification?.status).toBe("unknown");
expect(result.verification?.raw_stderr).toContain(
`${app}: invalid signature`,
);
expect(result.limitations).toContainEqual(
expect.stringContaining("Could not confirm completeness"),
);
expect(result.limitations).toContainEqual(
expect.stringContaining("permission denied (EACCES)"),
);
} finally {
await chmod(helpers, 0o755);
}
},
);
});
it("preserves failed display diagnostics through the caller-facing error contract", async () => {
const { app, executable } = await fixtureApp(undefined);
const diagnostic = `${executable}: permission denied while reading signature\n`;
const runner = new (class extends FixtureRunner {
override async run(tool: string, args: readonly string[]) {
const result = await super.run(tool, args);
return result.ok && args.includes("--verbose=4")
? ok({
...result.value,
exitCode: 1,
stderr: diagnostic,
stderrBytes: Buffer.byteLength(diagnostic),
})
: result;
}
})();
const result = await new NativeMacOSProvider(runner, "darwin")
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
expect(result.ok).toBe(false);
if (result.ok) throw new Error("Expected display failure");
expect(projectAnalysisError(result.error)).toMatchObject({
details: {
diagnostics: {
path: executable,
exit_code: 1,
raw_stderr: diagnostic,
arguments: ["-d", "--verbose=4", executable],
},
},
});
});
it("uses filesystem-confirmed newline ambiguity to qualify verification without losing raw evidence", async () => {
const { app, executable } = await fixtureApp(undefined);
const helpers = join(app, "Contents/Helpers");
await mkdir(helpers);
// A slash cannot be part of a POSIX basename. An absolute-looking continuation
// is represented by nested directories following the newline in the prefix.
const injected = join(helpers, `odd\n${app}: invalid signature`);
await mkdir(injected, { recursive: true });
const runner = new (class extends FixtureRunner {
override async run(tool: string, args: readonly string[]) {
const result = await super.run(tool, args);
if (!result.ok || args[0] !== "--verify") return result;
const stderr = `--prepared:${helpers}/odd\n${app}: invalid signature\n${app}: permission denied\n`;
return ok({
...result.value,
exitCode: 1,
stderr,
stderrBytes: Buffer.byteLength(stderr),
});
}
})();
const observed = await new NativeMacOSProvider(runner, "darwin")
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
if (!observed.ok) throw observed.error;
const result = inspectSignatureSchema.parse(observed.value.result);
expect(result.verification?.status).toBe("unknown");
expect(result.verification?.raw_stderr).toContain(
`${app}: invalid signature`,
);
expect(result.limitations).toContainEqual(
expect.stringContaining("structured nested-code records are ambiguous"),
);
});
/** Mutate only the fixture after its initial display has been observed. */
class ReplacingExecutableRunner extends FixtureRunner {
#changed = false;
override async run(tool: string, arguments_: readonly string[]) {
const result = await super.run(tool, arguments_);
if (
!this.#changed &&
tool === "codesign" &&
arguments_.includes("--verbose=4")
) {
const path = arguments_.at(-1);
if (path !== undefined)
await writeFile(path, "replacement executable bytes");
this.#changed = true;
}
return result;
}
}
/** A signed bundle whose nested helper is unsigned. */
class UnsignedNestedRunner extends FixtureRunner {
override async run(tool: string, arguments_: readonly string[]) {
const result = await super.run(tool, arguments_);
if (!result.ok || arguments_[0] !== "--verify") return result;
const stderr =
"/Applications/Fixture.app/Contents/Helpers/tool: code object is not signed at all\nIn subcomponent: /Applications/Fixture.app/Contents/Helpers/tool\n";
return ok({
...result.value,
stdout: "",
stderr,
stdoutBytes: 0,
stderrBytes: Buffer.byteLength(stderr),
exitCode: 1,
});
}
}
/** A platform binary whose `anchor apple` requirement check exits as given. */
class PlatformRunner extends FixtureRunner {
constructor(private readonly anchorExit: number) {
super();
}
override async run(tool: string, arguments_: readonly string[]) {
const result = await super.run(tool, arguments_);
if (!result.ok || tool !== "codesign") return result;
if (arguments_.includes("-R=anchor apple")) {
const target = arguments_.at(-1) ?? "";
const stderr =
this.anchorExit === 0
? ""
: `${target}: code failed to satisfy specified code requirement(s)\n`;
return ok({
...result.value,
exitCode: this.anchorExit,
stderr,
stderrBytes: Buffer.byteLength(stderr),
});
}
if (!arguments_.includes("--verbose=4")) return result;
const stderr = `${result.value.stderr}Platform identifier=26\n`;
return ok({
...result.value,
stderr,
stderrBytes: Buffer.byteLength(stderr),
});
}
}
/** A nested helper whose file name contains a newline. */
class NewlinePathRunner extends FixtureRunner {
override async run(tool: string, arguments_: readonly string[]) {
const result = await super.run(tool, arguments_);
if (!result.ok || arguments_[0] !== "--verify") return result;
const bundle = arguments_.at(-1) ?? "";
const stderr = `--validated:${bundle}/Contents/Helpers/odd\nname.app\n${bundle}: valid on disk\n`;
return ok({
...result.value,
stdout: "",
stderr,
stdoutBytes: 0,
stderrBytes: Buffer.byteLength(stderr),
});
}
}
/** Bundle verification fails on nested code while the main executable passes. */
class NestedOnlyFailureRunner extends FixtureRunner {
constructor(private readonly bundle: string) {
super();
}
override async run(tool: string, arguments_: readonly string[]) {
const result = await super.run(tool, arguments_);
if (!result.ok || arguments_[0] !== "--verify") return result;
if (arguments_.at(-1) !== this.bundle) return result;
const stderr = `${this.bundle}: a sealed resource is missing or invalid\nfile modified: ${this.bundle}/Contents/XPCServices/Svc.xpc\n`;
return ok({
...result.value,
stdout: "",
stderr,
stdoutBytes: 0,
stderrBytes: Buffer.byteLength(stderr),
exitCode: 1,
});
}
}
/**
* A universal binary whose aggregate display calls report the signed native
* slice while the x86_64 slice is unsigned.
*/
class UniversalMixedRunner extends FixtureRunner {
constructor(private readonly foreignArchitecture = "x86_64") {
super();
}
override async run(tool: string, arguments_: readonly string[]) {
const result = await super.run(tool, arguments_);
if (!result.ok || tool !== "codesign") return result;
const architectureIndex = arguments_.indexOf("-a");
if (architectureIndex >= 0) {
if (arguments_[architectureIndex + 1] !== this.foreignArchitecture)
return result;
const stderr = `${arguments_.at(-1)}: code object is not signed at all\n`;
return ok({
...result.value,
stdout: "",
stderr,
stdoutBytes: 0,
stderrBytes: Buffer.byteLength(stderr),
exitCode: 1,
});
}
if (!arguments_.includes("--verbose=4")) return result;
const stderr = result.value.stderr.replace(
/^Format=.*$/mu,
`Format=Mach-O universal (${this.foreignArchitecture} arm64)`,
);
return ok({
...result.value,
stderr,
stderrBytes: Buffer.byteLength(stderr),
});
}
}
/** Aggregate display succeeds, but per-architecture probes and verification fail operationally. */
class InconclusiveSlicesRunner extends FixtureRunner {
override async run(tool: string, arguments_: readonly string[]) {
const result = await super.run(tool, arguments_);
if (!result.ok || tool !== "codesign") return result;
if (!arguments_.includes("-a") && arguments_[0] !== "--verify")
return result;
const stderr = "I/O error reading signing data\n";
return ok({
...result.value,
stdout: "",
stderr,
exitCode: 1,
stdoutBytes: 0,
stderrBytes: Buffer.byteLength(stderr),
});
}
}
/** Slice display uncertainty and an independently established invalid signature. */
class DefiniteInvalidWithUncertainSlicesRunner extends InconclusiveSlicesRunner {
override async run(tool: string, arguments_: readonly string[]) {
const result = await super.run(tool, arguments_);
if (!result.ok || arguments_[0] !== "--verify") return result;
const stderr = `${arguments_.at(-1)}: invalid signature\n`;
return ok({
...result.value,
stderr,
stderrBytes: Buffer.byteLength(stderr),
});
}
}
/** A nested helper whose file name ends in a carriage return. */
class CarriageReturnPathRunner extends FixtureRunner {
override async run(tool: string, arguments_: readonly string[]) {
const result = await super.run(tool, arguments_);
if (!result.ok || arguments_[0] !== "--verify") return result;
const bundle = arguments_.at(-1) ?? "";
const stderr = `--validated:${bundle}/Contents/Helpers/cr\r\n${bundle}: valid on disk\n`;
return ok({
...result.value,
stdout: "",
stderr,
stdoutBytes: 0,
stderrBytes: Buffer.byteLength(stderr),
});
}
}
/**
* A universal binary whose slices all verify but carry different
* CodeDirectory flags (hardened arm64, plain x86_64).
*/
class UniversalPostureDiffRunner extends FixtureRunner {
override async run(tool: string, arguments_: readonly string[]) {
const result = await super.run(tool, arguments_);
if (!result.ok || tool !== "codesign") return result;
if (arguments_.includes("--entitlements")) return result;
const architectureIndex = arguments_.indexOf("-a");
const architecture =
architectureIndex < 0 ? null : arguments_[architectureIndex + 1];
let stderr = result.value.stderr;
if (architecture === null)
stderr = stderr.replace(
/^Format=.*$/mu,
"Format=Mach-O universal (x86_64 arm64)",
);
else if (architecture === "x86_64")
stderr = stderr.replace(
/flags=0x[0-9a-f]+\([^)]*\)/u,
"flags=0x2(adhoc)",
);
return ok({
...result.value,
stdout: "",
stderr,
stdoutBytes: 0,
stderrBytes: Buffer.byteLength(stderr),
});
}
}
/** Verification fails because nested code cannot be read. */
class PermissionDeniedRunner extends FixtureRunner {
override async run(tool: string, arguments_: readonly string[]) {
const result = await super.run(tool, arguments_);
if (!result.ok || arguments_[0] !== "--verify") return result;
const stderr = `${arguments_.at(-1)}: permission denied while reading nested code\n`;
return ok({
...result.value,
stdout: "",
stderr,
stdoutBytes: 0,
stderrBytes: Buffer.byteLength(stderr),
exitCode: 1,
});
}
}
/** Cancel the request once local verification has finished. */
class AbortAfterVerifyRunner extends FixtureRunner {
constructor(private readonly controller: AbortController) {
super();
}
override async run(tool: string, arguments_: readonly string[]) {
const result = await super.run(tool, arguments_);
if (arguments_[0] === "--verify") this.controller.abort();
return result;
}
}
+2 -9
View File
@@ -1,5 +1,4 @@
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import type { BinaryTarget } from "../../src/domain/binaryTarget.js";
import { ok } from "../../src/domain/result.js";
import type {
@@ -96,16 +95,10 @@ const capture = (
/** Build the Mach-O target identity used by native boundary fixtures. */
export const nativeMachoTarget = (
path: string,
/** The app bundle directory the target was opened from. */
bundle?: string,
sourcePath?: string,
): BinaryTarget => ({
path,
...(bundle === undefined
? {}
: {
sourcePath: bundle,
bundleInfoPlist: join(bundle, "Contents/Info.plist"),
}),
...(sourcePath === undefined ? {} : { sourcePath }),
sha256: "0".repeat(64),
kind: "executable",
format: "mach-o",
-19
View File
@@ -1,19 +0,0 @@
/** Synthetic local ticket framing; it does not contain an authenticated certificate/signature. */
export const notarizationTicketFixture = (): Uint8Array => {
const certificates = Buffer.from([0x30, 2, 0x30, 0]);
const content = Buffer.alloc(45);
content.write("g8tk", 0, "ascii");
content.writeUInt16LE(2, 4);
content.writeUInt16LE(20, 6);
content.writeUInt32LE(1, 8);
content[24] = 2;
content.fill(0xab, 25);
const signature = Buffer.alloc(72);
signature.set([0x30, 6, 2, 1, 1, 2, 1, 1]);
const header = Buffer.alloc(16);
header.write("s8ch", 0, "ascii");
header.writeUInt32LE(1, 4);
header.writeUInt32LE(certificates.length, 8);
header.writeUInt32LE(content.length, 12);
return Buffer.concat([header, certificates, content, signature]);
};