Files
reverse-engineering-anything/src/windows/WindowsNativeLoader.ts
T
morluto 5f718ce30e refactor(kernel): give error-message, byte-hex and SHA-256 hex helpers one owner in a new src/kernel layer (#11542)
* refactor(kernel): give error-to-message text one owner in a new src/kernel layer

* fix(kernel): keep the regex worker's own error text inside its isolated source

* refactor(kernel): exclude copies that run in another realm from the error-message guard by name

The regex worker's source string and the page.evaluate fetch in PlaywrightScenarioRequest cannot import errorMessage. The guard now names them, so the counted baseline does not invite a later slice to rewrite them.

* refactor(kernel): migrate the long tail of inline error-message copies to errorMessage (#11552)

Every provider and adapter folder with six or fewer copies now calls errorMessage from src/kernel. Local helpers whose whole body was the copy (failureMessage, gdbErrorMessage, message, describe, reasonOf, recoveryFailureMessage and four local errorMessage definitions) are removed and their call sites call the owner.

Refs #11548

* refactor(kernel): give byte-to-hex formatting one owner in src/kernel (#11560)

byteToHex returns the two lowercase hexadecimal digits of one byte. All eight inline copies (native, contracts, domain firmware and desktop, pcap) call it, keeping their own 0x, % or \x notation, and a counted guard with an empty baseline keeps new copies out.

Refs #11548

* refactor(kernel): give one-shot SHA-256 hex digests one owner in src/kernel (#11562)

sha256Hex digests one in-memory value. A counted guard records the one-shot createHash("sha256").update(x).digest("hex") chains (115 in 101 files) and the first slice migrates domain, contracts and process (35 copies), removing local wrappers (sha256, sha256Text, hash) and the exported sha256Text. Incremental and streamed hashing is not counted.

Refs #11548

* refactor(kernel): migrate the application layer's inline error-message copies to errorMessage (#11563)

All 69 copies in src/application call errorMessage from src/kernel. Local helpers whose whole body was the copy (errorDetail, causeReason and five local errorMessage definitions) are removed and their call sites call the owner.

Refs #11548

* refactor(kernel): migrate the native provider's inline error-message copies to errorMessage (#11567)

All 49 copies in src/native call errorMessage from src/kernel. The local errorReason helpers in LldbCallTracer and LldbRetainedObservations, whose whole body was the copy, are removed and their call sites call the owner.

Refs #11548

* refactor(kernel): migrate the remaining inline error-message copies to errorMessage (#11569)
2026-11-16 07:05:30 +08:00

280 lines
11 KiB
TypeScript

import { HOST_PLATFORM, type HostPlatform } from "../platform/HostPlatform.js";
import { readFileSync } from "node:fs";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
import { z } from "zod";
import { PACKAGE_METADATA } from "../generatedPackageMetadata.js";
import {
WINDOWS_NATIVE_ARTIFACT,
parseWindowsNativeManifest,
validateWindowsNativeArtifact,
} from "../domain/windowsNativeArtifact.js";
import { RuntimeControlUnavailableError } from "../domain/runtimeControlUnavailableError.js";
import { errorMessage } from "../kernel/errorMessage.js";
/** A native resource remains opaque until the addon validates its object tag. */
export const windowsHandleSchema = z.custom<object>(
(value): value is object =>
typeof value === "object" && value !== null && !Array.isArray(value),
);
/** Observed identity of an opened local NTFS or ReFS object. */
export const windowsFileIdentitySchema = z.strictObject({
requestedPath: z.string(),
finalPath: z.string(),
filesystem: z.enum(["NTFS", "ReFS"]),
volumeSerial: z.string().regex(/^[a-f0-9]{16}$/u),
fileId: z.string().regex(/^[a-f0-9]{32}$/u),
size: z.int().nonnegative().max(Number.MAX_SAFE_INTEGER),
directory: z.boolean(),
});
const inspectionSchema = z.strictObject({
abiVersion: z.literal(WINDOWS_NATIVE_ARTIFACT.abiVersion),
nodeApiVersion: z.literal(WINDOWS_NATIVE_ARTIFACT.nodeApiVersion),
architecture: z.literal(WINDOWS_NATIVE_ARTIFACT.architecture),
filesystem: windowsFileIdentitySchema,
privateDacl: z.literal(true),
privateBridgeDescriptorAccess: z.literal(true),
atomicJobAssignment: z.literal(true),
killOnOwnerClose: z.literal(true),
protocolStdin: z.boolean().optional(),
/** Absent from artifacts built before owned Job Object commit limits. */
jobMemoryLimit: z.literal(true).optional(),
});
type NativeCall = (
operation: string,
arguments_: readonly unknown[],
) => unknown;
const bindingSchema = z.strictObject({
call: z.custom<NativeCall>(
(value): value is NativeCall => typeof value === "function",
),
});
/** Validated native operations and the observations establishing readiness. */
export interface WindowsNativeAuthority {
readonly call: NativeCall;
readonly inspection: z.infer<typeof inspectionSchema>;
}
/** Availability of the bundled native implementation, including load failures. */
export type WindowsNativeLoadResult =
| { readonly available: true; readonly authority: WindowsNativeAuthority }
| {
readonly available: false;
readonly reason: string;
readonly failureStage:
| "host"
| "artifact"
| "load"
| "self-test"
| "inspection";
/** Only a failed native invocation can recover on a later query. */
readonly retryable?: true;
};
/** Trusted package reads and module loading, replaceable in loader tests. */
export interface WindowsNativeLoadHost {
readonly platform: NodeJS.Platform;
readonly architecture: string;
readonly nodeApiVersion: string | undefined;
readonly packageVersion: string;
readManifest(): unknown;
readArtifact(): Buffer;
loadArtifact(): unknown;
}
const missingWindowsNativeFileReason = (file: string): string =>
`Missing packaged Windows native file native/windows/build/${file} (ENOENT). Restore both native/windows/build/manifest.json and native/windows/build/rea-windows-x64.node from the rea-agents@${PACKAGE_METADATA.version} tarball or build them with native/windows/README.md; no native artifact was loaded.`;
/** Recovery when Windows refuses to load the verified artifact, for example by code-integrity policy. */
export const WINDOWS_NATIVE_LOAD_REFUSED_REMEDIATION =
"The file matched the package manifest, so restoring or reinstalling it will not help. If Windows reports that an Application Control policy blocked the file, Smart App Control or an App Control for Business policy refused it. Windows native controls, which Ghidra and JADX need on Windows, stay unavailable; rea setup can still register clients. Run REA on a host whose policy allows this file, or ask the REA maintainers about a signed build.";
export type WindowsNativeFailureStage = Exclude<
WindowsNativeLoadResult,
{ available: true }
>["failureStage"];
/** Stage-specific recovery guidance for an unavailable Windows native authority. */
export const windowsNativeFailureRemediation = (
failureStage: WindowsNativeFailureStage,
): string =>
failureStage === "host"
? "Use a Windows x64 host and a supported Node.js runtime with Node-API 8 or newer."
: failureStage === "load"
? WINDOWS_NATIVE_LOAD_REFUSED_REMEDIATION
: failureStage === "artifact"
? "Use the matching Windows x64 REA package, or restore native/windows/build/manifest.json and native/windows/build/rea-windows-x64.node from the same-version rea-agents tarball or build them with native/windows/README.md. The loader checks version, ABI, architecture, and digest before granting authority; no download or install is performed automatically."
: failureStage === "inspection"
? "Install the matching Windows x64 REA package; its native inspection must prove every required security control."
: "Inspect the preserved native self-test error. Check that the process has a writable local NTFS/ReFS temporary directory and that its filesystem, DACL, Job Object, and cleanup operations are permitted. Resolve the reported constraint, then rerun rea doctor; reinstalling Ghidra or Java cannot fix this self-test.";
/** Refusal when the Windows native authority cannot be loaded or self-tested before launch. */
export class WindowsNativeAuthorityUnavailableError extends RuntimeControlUnavailableError {
readonly code = "windows-native-authority-unavailable";
readonly failureStage: WindowsNativeFailureStage;
constructor(loaded: Exclude<WindowsNativeLoadResult, { available: true }>) {
super(loaded.reason, {
retryable: loaded.retryable === true,
remediationAction: windowsNativeFailureRemediation(loaded.failureStage),
});
this.name = "WindowsNativeAuthorityUnavailableError";
this.failureStage = loaded.failureStage;
}
}
const readPackagedWindowsNativeFile = <T>(file: string, read: () => T): T => {
try {
return read();
} catch (cause: unknown) {
if (
typeof cause === "object" &&
cause !== null &&
"code" in cause &&
cause.code === "ENOENT"
)
throw new Error(missingWindowsNativeFileReason(file), { cause });
throw cause;
}
};
/** Validate compatibility and artifact identity before invoking the native addon. */
export const loadWindowsNativeAuthority = (
host: WindowsNativeLoadHost,
): WindowsNativeLoadResult => {
if (host.platform !== "win32" || host.architecture !== "x64")
return {
available: false,
failureStage: "host",
reason: "REA Windows native controls require a Windows x64 host.",
};
const nodeApiVersion = Number(host.nodeApiVersion);
if (
!Number.isSafeInteger(nodeApiVersion) ||
nodeApiVersion < WINDOWS_NATIVE_ARTIFACT.nodeApiVersion
)
return {
available: false,
failureStage: "host",
reason: "REA Windows native controls require Node-API 8 or newer.",
};
try {
const manifest = parseWindowsNativeManifest(
readPackagedWindowsNativeFile("manifest.json", () => host.readManifest()),
host.packageVersion,
);
if (!manifest.ok) throw manifest.error;
const artifact = readPackagedWindowsNativeFile(
WINDOWS_NATIVE_ARTIFACT.artifact,
() => host.readArtifact(),
);
const valid = validateWindowsNativeArtifact(manifest.value, artifact);
if (!valid.ok) throw valid.error;
let loadedModule: unknown;
try {
loadedModule = host.loadArtifact();
} catch (cause: unknown) {
return {
available: false,
failureStage: "load",
reason: `REA Windows native controls are unavailable: Windows refused to load the verified native/windows/build/rea-windows-x64.node: ${errorMessage(cause)} ${WINDOWS_NATIVE_LOAD_REFUSED_REMEDIATION}`,
};
}
const binding = bindingSchema.parse(loadedModule);
let observed: unknown;
try {
observed = binding.call("inspect", []);
} catch (cause: unknown) {
return {
available: false,
failureStage: "self-test",
retryable: true,
reason: `REA Windows native self-test failed: ${errorMessage(cause)}`,
};
}
const parsed = inspectionSchema.safeParse(observed);
if (!parsed.success)
return {
available: false,
failureStage: "inspection",
reason: `REA Windows native inspection is invalid: ${parsed.error.message}`,
};
const inspection = parsed.data;
return { available: true, authority: { call: binding.call, inspection } };
} catch (cause: unknown) {
return {
available: false,
failureStage: "artifact",
reason: `REA Windows native controls are unavailable: ${errorMessage(cause)}`,
};
}
};
let cached: WindowsNativeLoadResult | undefined;
const loadPackagedWindowsNativeAuthority = ({
platform,
architecture,
}: HostPlatform): WindowsNativeLoadResult =>
loadWindowsNativeAuthority({
platform,
architecture,
nodeApiVersion: process.versions.napi,
packageVersion: PACKAGE_METADATA.version,
readManifest: () => {
const encoded = readFileSync(
new URL("../../native/windows/build/manifest.json", import.meta.url),
"utf8",
);
const value: unknown = JSON.parse(encoded);
return value;
},
readArtifact: () =>
readFileSync(
new URL(
"../../native/windows/build/rea-windows-x64.node",
import.meta.url,
),
),
loadArtifact: () => {
const value: unknown = createRequire(import.meta.url)(
fileURLToPath(
new URL(
"../../native/windows/build/rea-windows-x64.node",
import.meta.url,
),
),
);
return value;
},
});
/**
* Cache stable admission; let a later query retry failed owned inspection.
* Only this host's result is cached: another host's admission rules are a
* test seam and load the packaged artifact uncached.
*/
export const systemWindowsNativeAuthority = (
host: HostPlatform = HOST_PLATFORM,
): WindowsNativeLoadResult => {
if (host !== HOST_PLATFORM) return loadPackagedWindowsNativeAuthority(host);
if (cached?.available === false && cached.retryable === true)
cached = undefined;
cached ??= loadPackagedWindowsNativeAuthority(host);
return cached;
};
/** Require the verified backend when an operation depends on native authority. */
export const requireWindowsNativeAuthority = (): WindowsNativeAuthority => {
const loaded = systemWindowsNativeAuthority();
if (!loaded.available)
throw new WindowsNativeAuthorityUnavailableError(loaded);
return loaded.authority;
};